简体   繁体   中英

How to properly define getters for class variables in Ruby?

I decided to write small Rails model concern which allows my models to be sluggable. This concern provides method which can be used to redefine slug column. Currently it works, but I am not sure if my code does not smell. First of all I want to know if I can use any shortcut to define getter for class variable.

Probably my code should be refactored. Here it goes:

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

When I use rubocop gem I get warnings about sluggable_attribute class method with notice that I use should use attr_reader for trivial reader methods.

Please advise how I should improve my code to fit Ruby and Rails conventions.

Thank you!

Since you are in the context of Rails i recommend you the 'class_attribute' method ( doc here ). In my opinion is most appropriate for rails gems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM