mattr_writer(*syms)
Instance Public methods
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute.
1 2 3 4 5 6 7 8 9 10 11 12 | 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] |
If you want to opt out the instance writer method, pass
instance_writer: false
or instance_accessor:
false
.
1 2 3 4 5 6 7 8 9 | module HairColors mattr_writer :hair_colors , instance_writer: false end class Person include HairColors end Person. new .hair_colors = [ :blonde , :red ] # => 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 | class HairColors mattr_writer :hair_colors do [ :brown , :black , :blonde , :red ] end end class Person include HairColors end Person.class_variable_get( "@@hair_colors" ) # => [:brown, :black, :blonde, :red] |
Please login to continue.