instance method mattr_writer

Ruby on Rails 6.0.6

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_writer(*syms, instance_writer: true, instance_accessor: true, default: nil)

Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute. 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_writer :hair_colors
end

class Person
  include HairColors
end

HairColors.hair_colors = [:brown, :black]
Person.class_variable_get("@@hair_colors") # => [:brown, :black]
Person.new.hair_colors = [:blonde, :red]
HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]

To omit the instance writer method, pass instance_writer: false or instance_accessor: false.

module HairColors
  mattr_writer :hair_colors, instance_writer: false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:blonde, :red] # => NoMethodError

You can set a default value for the attribute.

module HairColors
  mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red]
end

class Person
  include HairColors
end

Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]

Parameters

syms rest
instance_writer key = true
instance_accessor key = true
default key = nil
Source
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 118
  def mattr_writer(*syms, instance_writer: 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}=(obj)
          @@#{sym} = obj
        end
      EOS

      if instance_writer && instance_accessor
        class_eval(<<-EOS, __FILE__, __LINE__ + 1)
          def #{sym}=(obj)
            @@#{sym} = obj
          end
        EOS
      end

      sym_default_value = (block_given? && default.nil?) ? yield : default
      send("#{sym}=", sym_default_value) unless sym_default_value.nil?
    end
  end

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

Defined in Module

Type at least 2 characters to search.

↑↓ navigate · open · esc close