Method: Class#cattr_reader

Defined in:
motion/core_ext/class/attribute_accessors.rb

#cattr_reader(*syms) ⇒ Object

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


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'motion/core_ext/class/attribute_accessors.rb', line 30

def cattr_reader(*syms)
  options = syms.extract_options!
  syms.each do |sym|
    raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
    class_exec do
      unless class_variable_defined?("@@#{sym}")
        class_variable_set("@@#{sym}", nil)
      end

      define_singleton_method sym do
        class_variable_get("@@#{sym}")
      end
    end

    unless options[:instance_reader] == false || options[:instance_accessor] == false
      class_exec do
        define_method sym do
          self.class.class_variable_get("@@#{sym}")
        end
      end
    end
  end
end