instance method cattr_writer

Ruby on Rails 4.0.13

Since v2.2.3 Last seen in v4.0.13

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13

Signature

cattr_writer(*syms)

Defines a class attribute if it’s not defined and creates a writer method to allow assignment to the attribute.

class Person
  cattr_writer :hair_colors
end

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

The attribute name must be a valid method name in Ruby.

class Person
  cattr_writer :"1_Badname "
end
# => NameError: invalid attribute name

If you want to opt out the instance writer method, pass instance_writer: false or instance_accessor: false.

class Person
  cattr_writer :hair_colors, instance_writer: false
end

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

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

class Person
  cattr_writer :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end

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

Parameters

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

        def self.#{sym}=(obj)
          @@#{sym} = obj
        end
      EOS

      unless options[:instance_writer] == false || options[:instance_accessor] == false
        class_eval(<<-EOS, __FILE__, __LINE__ + 1)
          def #{sym}=(obj)
            @@#{sym} = obj
          end
        EOS
      end
      send("#{sym}=", yield) if block_given?
    end
  end

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

Defined in Class

Type at least 2 characters to search.

↑↓ navigate · open · esc close