ayushn21
ayushn21

Reputation: 305

What the difference between a Ruby class level variable and a Rails class_attribute?

Is there any difference between a class level variable (@@something), and defining a class_attribute (https://apidock.com/rails/Class/class_attribute) in Rails?

For example, in these two code snippets, will there be any difference in behaviour?

class Adaptee
  def self.adapter=(adapter)
    @@adapter = adapter
  end
end
class Adaptee
  class_attribute :adapter
end

Upvotes: 0

Views: 279

Answers (1)

mechnicov
mechnicov

Reputation: 15288

Most important difference is that class_attribute is not inherit.

For example we have:

class Parent
  class_attribute :klass_atr
  @@klass_var = :foo

  class << self
    def klass_atr
      :foo
    end

    def klass_var
      @@klass_var
    end

    def klass_var=(klass_var)
      @@klass_var = klass_var
    end
  end
end

class Child < Parent; end

When we assign class variable in Сhild we change it in Parent too:

Child.klass_var = :bar
Parent.klass_var # => :bar

But when we use class_attribute, we don't:

Child.klass_atr = :bar
Parent.klass_atr # => :foo

That's why most popular Ruby style guide doesn't recommend to use class variables.

Upvotes: 3

Related Questions