instance method
cattr_accessor
Ruby on Rails 3.2.22.5
Since v2.2.3 Last seen in v4.0.13Signature
cattr_accessor(*syms, &blk)
Defines both class and instance accessors for class attributes.
class Person cattr_accessor :hair_colors 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.
class Person cattr_accessor :hair_colors, :instance_writer => false, :instance_reader => false end Person.new.hair_colors = [:brown] # => NoMethodError Person.new.hair_colors # => NoMethodError
Or pass :instance_accessor => false, to opt out both instance methods.
class Person cattr_accessor :hair_colors, :instance_accessor => false 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.
class Person cattr_accessor :hair_colors do [:brown, :black, :blonde, :red] end end Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
Parameters
-
symsrest -
blkblock
Source
# File activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 164
def cattr_accessor(*syms, &blk)
cattr_reader(*syms)
cattr_writer(*syms, &blk)
end
Defined in activesupport/lib/active_support/core_ext/class/attribute_accessors.rb line 164
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Class