instance method
mattr_accessor
Ruby on Rails 5.2.8.1
Signature
mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
Defines both class and instance accessors for class attributes. All class and instance methods created will be public, even if this method is called with a private or protected access modifier.
module HairColors
mattr_accessor :hair_colors
end
class Person
include HairColors
end
HairColors.hair_colors = [:brown, :black, :blonde, :red]
HairColors.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.new.hair_colors << :blue
Person.new.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
You can set a default value for the attribute.
module HairColors
mattr_accessor :hair_colors, default: [:brown, :black, :blonde, :red]
end
class Person
include HairColors
end
Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
Parameters
-
symsrest -
instance_readerkey = true -
instance_writerkey = true -
instance_accessorkey = true -
defaultkey = nil -
blkblock
Source
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 210
def mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default, &blk)
mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor, default: default)
end
Defined in activesupport/lib/active_support/core_ext/module/attribute_accessors.rb line 210
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Module