【问题标题】:How to properly define getters for class variables in Ruby?如何在 Ruby 中正确定义类变量的 getter?
【发布时间】: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


【解决方案1】:

由于您使用的是 Rails,我建议您使用“class_attribute”方法 (doc here)。我认为最适合 Rails 宝石。

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 2020-06-20
    • 2011-06-03
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多