mattr_accessor

mattr_accessor(*syms, &blk)
Instance Public methods

Defines both class and instance accessors for class attributes.

1
2
3
4
5
6
7
8
9
10
11
module HairColors
  mattr_accessor :hair_colors
end
 
class Person
  include HairColors
end
 
Person.hair_colors = [:brown, :black, :blonde, :red]
Person.hair_colors     # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]

If a subclass changes the value then that would also change the value for parent class. Similarly if parent class changes the value then that would change the value of subclasses too.

1
2
3
4
5
class Male < Person
end
 
Male.hair_colors << :blue
Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]

To opt out of the instance writer method, pass instance_writer: false. To opt out of the instance reader method, pass instance_reader: false.

1
2
3
4
5
6
7
8
9
10
module HairColors
  mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
end
 
class Person
  include HairColors
end
 
Person.new.hair_colors = [:brown# => NoMethodError
Person.new.hair_colors             # => NoMethodError

Or pass instance_accessor: false, to opt out both instance methods.

1
2
3
4
5
6
7
8
9
10
module HairColors
  mattr_accessor :hair_colors, instance_accessor: false
end
 
class Person
  include HairColors
end
 
Person.new.hair_colors = [:brown# => NoMethodError
Person.new.hair_colors             # => NoMethodError

Also you can pass a block to set up the attribute with a default value.

1
2
3
4
5
6
7
8
9
10
11
module HairColors
  mattr_accessor :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end
 
class Person
  include HairColors
end
 
Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]

cattr_accessor

doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.