instance method
mattr_reader
Ruby on Rails 5.2.8.1
Signature
mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
Defines a class attribute and creates a class and instance reader methods. The underlying class variable is set to nil, if it is not previously defined. All class and instance methods created will be public, even if this method is called with a private or protected access modifier.
module HairColors
mattr_reader :hair_colors
end
HairColors.hair_colors # => nil
HairColors.class_variable_set("@@hair_colors", [:brown, :black])
HairColors.hair_colors # => [:brown, :black]
The attribute name must be a valid method name in Ruby.
module Foo
mattr_reader :"1_Badname"
end
# => NameError: invalid attribute name: 1_Badname
If you want to opt out the creation on the instance reader method, pass instance_reader: false or instance_accessor: false.
module HairColors
mattr_reader :hair_colors, instance_reader: false
end
class Person
include HairColors
end
Person.new.hair_colors # => NoMethodError
You can set a default value for the attribute.
module HairColors
mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red]
end
class Person
include HairColors
end
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
Parameters
-
symsrest -
instance_readerkey = true -
instance_accessorkey = true -
defaultkey = nil
Source
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 54
def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
syms.each do |sym|
raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym)
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@#{sym} = nil unless defined? @@#{sym}
def self.#{sym}
@@#{sym}
end
EOS
if instance_reader && instance_accessor
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
@@#{sym}
end
EOS
end
sym_default_value = (block_given? && default.nil?) ? yield : default
class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil?
end
end
Defined in activesupport/lib/active_support/core_ext/module/attribute_accessors.rb line 54
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Module