class Module
def mattr_writer(*syms)
end
include HairColors
class Person
end
end
[:brown, :black, :blonde, :red]
mattr_writer :hair_colors do
module HairColors
Also, you can pass a block to set up the attribute with a default value.
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.
If you want to opt out 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
allow assignment to the attribute.
Defines a class attribute and creates a class and instance writer methods to
def mattr_writer(*syms) options = syms.extract_options! syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /\A[_A-Za-z]\w*\z/ class_eval(<<-EOS, __FILE__, __LINE__ + 1) @@#{sym} = nil unless defined? @@#{sym} def self.#{sym}=(obj) @@#{sym} = obj end EOS unless options[:instance_writer] == false || options[:instance_accessor] == false class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{sym}=(obj) @@#{sym} = obj end EOS end send("#{sym}=", yield) if block_given? end end