class Module
def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil)
end
include HairColors
class Person
end
mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red]
module HairColors
You can set a default value for the attribute.
Person.new.hair_colors # => NoMethodError
end
include HairColors
class Person
end
mattr_reader :hair_colors, instance_reader: false
module HairColors
instance_reader: false or instance_accessor: false.
To omit the instance reader method, pass
# => NameError: invalid attribute name: 1_Badname
end
mattr_reader :"1_Badname"
module Foo
The attribute name must be a valid method name in Ruby.
HairColors.hair_colors # => [:brown, :black]
HairColors.class_variable_set("@@hair_colors", [:brown, :black])
HairColors.hair_colors # => nil
end
mattr_reader :hair_colors
module HairColors
this method is called with a private or protected access modifier.
defined. All class and instance methods created will be public, even if
The underlying class variable is set to +nil+, if it is not previously
Defines a class attribute and creates a class and instance reader methods.
def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil) raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class? location ||= caller_locations(1, 1).first definition = [] syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) definition << "def self.#{sym}; @@#{sym}; end" if instance_reader && instance_accessor definition << "def #{sym}; @@#{sym}; end" end sym_default_value = (block_given? && default.nil?) ? yield : default class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? && class_variable_defined?("@@#{sym}") end module_eval(definition.join(";"), location.path, location.lineno) end