method
mattr_writer
v8.1.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 (5)
- 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 (4)
- 7.1.3.4 (0)
- 7.2.3 (0)
- 8.0.0 (0)
- 8.1.1 (0)
- What's this?
mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil)
public
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute. All class and instance methods created will be public, even if this method is called with a private or protected access modifier.
module HairColors mattr_writer :hair_colors end class Person include HairColors end HairColors.hair_colors = [:brown, :black] Person.class_variable_get("@@hair_colors") # => [:brown, :black] Person.new.hair_colors = [:blonde, :red] HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]
To omit the instance writer method, pass instance_writer: false or instance_accessor: false.
module HairColors mattr_writer :hair_colors, instance_writer: false end class Person include HairColors end Person.new.hair_colors = [:blonde, :red] # => NoMethodError
You can set a default value for the attribute.
module HairColors mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red] mattr_writer(:hair_styles) { [:long, :short] } end class Person include HairColors end Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] Person.class_variable_get("@@hair_styles") # => [:long, :short]

