instance method
mattr_writer
Ruby on Rails 4.2.9
Since v2.2.3Signature
mattr_writer(*syms)
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]
Parameters
-
symsrest
Source
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 119
def mattr_writer(*syms)
options = syms.extract_options!
syms.each do |sym|
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
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
Defined in activesupport/lib/active_support/core_ext/module/attribute_accessors.rb line 119
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Module