Timur Khafizov
Timur Khafizov

Reputation: 15

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 rubocopgem 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!

Upvotes: 1

Views: 325

Answers (1)

Armando
Armando

Reputation: 940

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.

Upvotes: 1

Related Questions