如何在Ruby中正确定义类变量的getter?

时间:2014-08-30 18:02:54

标签: ruby-on-rails ruby ruby-on-rails-4 refactoring

我决定编写小型Rails模型,让我的模型可以缓慢。 这种关注提供了可用于重新定义段塞柱的方法。 目前它的工作原理,但我不确定我的代码是否闻不到。 首先,我想知道是否可以使用任何快捷方式为类变量定义getter。

可能我的代码应该重构。在这里:

module Sluggable
  extend ActiveSupport::Concern

  included do
    extend FriendlyId

    slug_with :name

    def should_generate_new_friendly_id?
      slug.blank? || sluggable_attribute_changed?
    end

    def sluggable_attribute_changed?
      public_send("#{self.class.sluggable_attribute}_changed?")
    end
  end

  module ClassMethods
    def slug_with(attribute)
      @sluggable_attribute = attribute

      apply_friendly_id(@sluggable_attribute)
    end

    def apply_friendly_id(sluggable_attribute)
      friendly_id sluggable_attribute, use: %w(slugged history)
    end

    def sluggable_attribute
      @sluggable_attribute
    end
  end
end

当我使用rubocop gem时,我会收到关于sluggable_attribute类方法的警告,并注意我使用的attr_reader应该使用简单的读者方法。

请告知我应该如何改进我的代码以适应Ruby和Rails惯例。

谢谢!

1 个答案:

答案 0 :(得分:1)

由于您处于Rails环境中,我建议您使用&class; class_attribute'方法(doc here)。在我看来,最适合rails gems。