我试图通过一种被所有控制器继承的方法来限制RoR应用程序中API的内容类型。
CONTENT_TYPE = 'application/vnd.api+json'
def restrict_content_Type
return if request.content_type = CONTENT_TYPE
render_content_type_error
end
这很好用,但是现在我必须对单个端点和控制器使用不同的内容类型,并且我想在重用已有代码的同时更改CONTENT_TYPE
常量的内容。要使用其他常量,我必须使用读取器方法在当前控制器中查找常量。
我将代码重构为:
def get_content_type
self::CONTENT_TYPE
end
def restrict_content_type
return if request.content_type == get_content_type
...
end
我使用get_*
阅读器的原因是self.content_type返回Request
的内容类型:https://api.rubyonrails.org/classes/ActionDispatch/Response.html#method-i-content_type
在这一点上,Rubocop由于我使用的名字而抱怨,get_*
阅读器不是惯用的Ruby。
我当然可以在rubocop中重写此行为,但是我想听听我的其他选择以及是否有其他解决方案,因为我也不喜欢该方法的名称。
有什么主意吗?