Flowdock

Extends the class object with class and instance accessors for class attributes, just like the native attr* accessors for instance attributes.

Note that unlike class_attribute, 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 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]

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

It is recommended to use class_attribute over methods defined in this file. Please refer to documentation for class_attribute for more information. Officially it is not deprecated but class_attribute is faster.

Allows attributes to be shared within an inheritance hierarchy. Each descendant gets a copy of their parents’ attributes, instead of just a pointer to the same. This means that the child can add elements to, for example, an array without those additions being shared with either their parent, siblings, or children. This is unlike the regular class-level attributes that are shared across the entire hierarchy.

The copies of inheritable parent attributes are added to subclasses when they are created, via the inherited hook.

class Person
  class_inheritable_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]

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
  class_inheritable_accessor :hair_colors :instance_writer => false, :instance_reader => false
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError

Constants

EMPTY_INHERITABLE_ATTRIBUTES = {}.freeze

Attributes

Show files where this class is defined (6 files)
Register or log in to add new notes.