mattr_writer

mattr_writer(*syms)
Instance Public methods

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]

cattr_writer

doc_ruby_on_rails
2015-06-20 00:00:00
Comments
Leave a Comment

Please login to continue.