method
mattr_reader
v5.0.0.1 -
Show latest stable
-
0 notes -
Class: Module
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (0)
- 4.1.8 (38)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (4)
- 5.2.3 (-1)
- 6.0.0 (-1)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (3)
- 7.1.3.4 (0)
- 7.2.3 (0)
- 8.0.0 (0)
- 8.1.1 (0)
- What's this?
mattr_reader(*syms)
public
Defines a class attribute and creates a class and instance reader methods. The underlying class variable is set to nil, if it is not previously defined.
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.
module Foo mattr_reader :"1_Badname" end # => NameError: invalid attribute name: 1_Badname
If you want to opt out the creation on the instance reader method, pass instance_reader: false or instance_accessor: false.
module HairColors mattr_reader :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.
module HairColors mattr_reader :hair_colors do [:brown, :black, :blonde, :red] end end class Person include HairColors end Person.new.hair_colors # => [:brown, :black, :blonde, :red]

