我决定编写小型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惯例。
谢谢!
答案 0 :(得分:1)
由于您处于Rails环境中,我建议您使用&class; class_attribute'方法(doc here)。在我看来,最适合rails gems。