instance method
cattr_reader
Ruby on Rails 3.2.22.5
Last seen in v4.0.13Signature
cattr_reader(*syms)
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
Parameters
-
symsrest
Source
# File activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 32
def cattr_reader(*syms)
options = syms.extract_options!
syms.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
unless defined? @@#{sym}
@@#{sym} = nil
end
def self.#{sym}
@@#{sym}
end
EOS
unless options[:instance_reader] == false || options[:instance_accessor] == false
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
@@#{sym}
end
EOS
end
end
end
Defined in activesupport/lib/active_support/core_ext/class/attribute_accessors.rb line 32
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Class