Method: Class#cattr_accessor

Defined in:
activesupport/lib/active_support/core_ext/class/attribute_accessors.rb

#cattr_accessor(*syms, &blk) ⇒ Object

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]


166
167
168
169
# File 'activesupport/lib/active_support/core_ext/class/attribute_accessors.rb', line 166

def cattr_accessor(*syms, &blk)
  cattr_reader(*syms)
  cattr_writer(*syms, &blk)
end