method

cattr_reader

v4.0.2 - Show latest stable - Class: Class
cattr_reader(*syms)
public

Defines a class attribute if it’s not defined and creates a reader method that returns the attribute value.

class Person
  cattr_reader :hair_colors
end

Person.class_variable_set("@@hair_colors", [:brown, :black])
Person.hair_colors     # => [:brown, :black]
Person.new.hair_colors # => [:brown, :black]

The attribute name must be a valid method name in Ruby.

class Person
  cattr_reader :"1_Badname "
end
# => NameError: invalid attribute name

If you want to opt out the instance reader method, you can pass instance_reader: false or instance_accessor: false.

class Person
  cattr_reader :hair_colors, instance_reader: false
end

Person.new.hair_colors # => NoMethodError

1Note

Other Example

jackson_pires · Feb 2, 2013
##

class Exam cattr_reader :code, :description, :points, :instance_reader => false

@@code = "EXM"
@@description = "Sent Exam"
@@points = 1000

end

=== In this case it's possible to use

Exam.code # => EXM Exam.description # => Sent Exam Exam.points # => 1000