我试图通过一种被所有控制器继承的方法来限制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中重写此行为,但是我想听听我的其他选择以及是否有其他解决方案,因为我也不喜欢该方法的名称。
有什么主意吗?
答案 0 :(得分:0)
您可以使用其他一些名称来表明此方法的目的,例如current_content_type
,restricted_content_type
,disabled_content_type
-最适合您的情况。
答案 1 :(得分:0)
关于命名,最好有一个名为invalid_content_type?
的方法,该方法返回一个Boolean
。
例如:
def invalid_content_type?(content_type)
request.content_type == content_type
end
def restrict_content_type
return if invalid_content_type(self::CONTENT_TYPE)
...
end