author avatar

nived.hari

Sun Dec 22 2024

mattr_accessor is a Rails utility method that creates a class-level accessor for a variable.
When we define mattr_accessor for a variable, it creates
1. A getter method for the class.
2. A setter method for the class.
Eg:


class MyClass
  mattr_accessor :my_variable
end


This is equivalent to:


class MyClass
  @my_variable = nil

  def self.my_variable
    @my_variable
  end

  def self.my_variable=(value)
    @my_variable = value
  end
end


It also works on module-level classes, which makes it particularly useful for defining global configuration in gems.

#CU6U0R822