【问题标题】:Naming getter method with 'get_' when attribute is already present当属性已经存在时,用 'get_' 命名 getter 方法
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      关于命名,最好有一个名为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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 2022-11-30
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-20
        相关资源
        最近更新 更多