instance method mattr_reader

Ruby on Rails 4.2.9

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

mattr_reader(*syms)

Defines a class attribute and creates a class and instance reader methods. The underlying the class variable is set to nil, if it is not previously defined.

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

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

module HairColors
  mattr_writer :hair_colors, instance_reader: false
end

class Person
  include HairColors
end

Person.new.hair_colors # => NoMethodError

Also, you can pass a block to set up the attribute with a default value.

module HairColors
  cattr_reader :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end

class Person
  include HairColors
end

Person.hair_colors # => [:brown, :black, :blonde, :red]

Parameters

syms rest
Source
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 53
  def mattr_reader(*syms)
    options = syms.extract_options!
    syms.each do |sym|
      raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
        @@#{sym} = nil unless defined? @@#{sym}

        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
      class_variable_set("@@#{sym}", yield) if block_given?
    end
  end

Defined in activesupport/lib/active_support/core_ext/module/attribute_accessors.rb line 53 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Module

Type at least 2 characters to search.

↑↓ navigate · open · esc close