当属性已经存在时,用'get_'命名吸气剂方法

问题描述 投票:1回答:2

我正在尝试使用一种被所有控制器继承的方法来限制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中重写此行为,但是我想听听我的其他选择以及是否有其他解决方案,因为我也不喜欢该方法的名称。

任何想法?

ruby-on-rails ruby oop naming
2个回答
0
投票

您可以使用其他一些名称来表明此方法的目的,例如current_content_typerestricted_content_typedisabled_content_type-最适合您的方式。


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
© www.soinside.com 2019 - 2024. All rights reserved.