mattr_reader

mattr_reader(*syms)
Instance Public methods

Defines a class attribute and creates a class and instance reader methods. The underlying the class variable is set to nil, if it is not previously defined.

1
2
3
4
5
6
7
module HairColors
  mattr_reader :hair_colors
end
 
HairColors.hair_colors # => nil
HairColors.class_variable_set("@@hair_colors", [:brown, :black])
HairColors.hair_colors # => [:brown, :black]

The attribute name must be a valid method name in Ruby.

1
2
3
4
module Foo
  mattr_reader :"1_Badname "
end
# => NameError: invalid attribute name

If you want to opt out the creation on the instance reader method, pass instance_reader: false or instance_accessor: false.

1
2
3
4
5
6
7
8
9
module HairColors
  mattr_writer :hair_colors, instance_reader: false
end
 
class Person
  include HairColors
end
 
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
  cattr_reader :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end
 
class Person
  include HairColors
end
 
Person.hair_colors # => [:brown, :black, :blonde, :red]

cattr_reader

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

Please login to continue.