instance method
mattr_accessor
Ruby on Rails 4.2.9
Signature
mattr_accessor(*syms, &blk)
Defines both class and instance accessors for class attributes.
module HairColors
mattr_accessor :hair_colors
end
class Person
include HairColors
end
Person.hair_colors = [:brown, :black, :blonde, :red]
Person.hair_colors # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
If a subclass changes the value then that would also change the value for parent class. Similarly if parent class changes the value then that would change the value of subclasses too.
class Male < Person
end
Male.hair_colors << :blue
Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
To opt out of the instance writer method, pass instance_writer: false. To opt out of the instance reader method, pass instance_reader: false.
module HairColors
mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
end
class Person
include HairColors
end
Person.new.hair_colors = [:brown] # => NoMethodError
Person.new.hair_colors # => NoMethodError
Or pass instance_accessor: false, to opt out both instance methods.
module HairColors
mattr_accessor :hair_colors, instance_accessor: false
end
class Person
include HairColors
end
Person.new.hair_colors = [:brown] # => NoMethodError
Person.new.hair_colors # => NoMethodError
Also you can pass a block to set up the attribute with a default value.
module HairColors
mattr_accessor :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 -
blkblock
Source
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 207
def mattr_accessor(*syms, &blk)
mattr_reader(*syms, &blk)
mattr_writer(*syms, &blk)
end
Defined in activesupport/lib/active_support/core_ext/module/attribute_accessors.rb line 207
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Module