class Module
def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil)
end
include HairColors
class Person
end
mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red]
module HairColors
You can set a default value for the attribute.
Person.new.hair_colors = [:blonde, :red] # => NoMethodError
end
include HairColors
class Person
end
mattr_writer :hair_colors, instance_writer: false
module HairColors
instance_writer: false or instance_accessor: false.
To omit the instance writer method, pass
HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]
Person.new.hair_colors = [:blonde, :red]
Person.class_variable_get("@@hair_colors") # => [:brown, :black]
HairColors.hair_colors = [:brown, :black]
end
include HairColors
class Person
end
mattr_writer :hair_colors
module HairColors
access modifier.
will be public, even if this method is called with a private or protected
allow assignment to the attribute. All class and instance methods created
Defines a class attribute and creates a class and instance writer methods to
def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil) raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class? location ||= caller_locations(1, 1).first definition = [] syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) definition << "def self.#{sym}=(val); @@#{sym} = val; end" if instance_writer && instance_accessor definition << "def #{sym}=(val); @@#{sym} = val; end" end sym_default_value = (block_given? && default.nil?) ? yield : default class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? && class_variable_defined?("@@#{sym}") end module_eval(definition.join(";"), location.path, location.lineno) end