method
mattr_writer
mattr_writer(*syms)
public
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute.
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.
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.
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]