【发布时间】:2014-08-30 18:02:53
【问题描述】:
我决定编写一个小的 Rails 模型关注点,它可以让我的模型成为 sluggable。 这种关注提供了可用于重新定义段塞柱的方法。 目前它可以工作,但我不确定我的代码是否有异味。 首先我想知道是否可以使用任何快捷方式为类变量定义 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
当我使用 rubocopgem 时,我收到有关 sluggable_attribute 类方法的警告,并通知我应该使用 attr_reader 来获取琐碎的读取器方法。
请告知我应该如何改进我的代码以适应 Ruby 和 Rails 约定。
谢谢!
【问题讨论】:
-
可以为实例变量定义访问器,而不是类变量。我假设您指的是类实例变量,无论如何您都应该使用它而不是类变量。为类实例变量定义访问器的常规方法如下:
class << self; attr_accessor var; end。另请参阅cattr_accessor。
标签: ruby-on-rails ruby ruby-on-rails-4 refactoring