【发布时间】:2020-03-17 07:12:46
【问题描述】:
我正在尝试在 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_*readers 不是惯用的 Ruby。
我当然可以在 rubocop 中覆盖此行为,但我想知道我的其他选择是什么以及是否有其他解决方案,因为我也不喜欢该方法的名称。
有什么想法吗?
【问题讨论】:
标签: ruby-on-rails ruby oop naming