class method self.attribute

Ruby on Rails 8.1.2

Since v5.2.8.1

Available in: 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

self.attribute(*names, default: NOT_SET)

Declares one or more attributes that will be given both class and instance accessor methods.

Options

  • :default - The default value for the attributes. If the value is a proc or lambda, it will be called whenever an instance is constructed. Otherwise, the value will be duplicated with #dup. Default values are re-assigned when the attributes are reset.

Parameters

names rest
default key = NOT_SET
Source
# File activesupport/lib/active_support/current_attributes.rb, line 115
      def attribute(*names, default: NOT_SET)
        invalid_attribute_names = names.map(&:to_sym) & INVALID_ATTRIBUTE_NAMES
        if invalid_attribute_names.any?
          raise ArgumentError, "Restricted attribute names: #{invalid_attribute_names.join(", ")}"
        end

        Delegation.generate(singleton_class, names, to: :instance, nilable: false, signature: "")
        Delegation.generate(singleton_class, names.map { |n| "#{n}=" }, to: :instance, nilable: false, signature: "value")

        ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |owner|
          names.each do |name|
            owner.define_cached_method(name, namespace: :current_attributes) do |batch|
              batch <<
                "def #{name}" <<
                "@attributes[:#{name}]" <<
                "end"
            end
            owner.define_cached_method("#{name}=", namespace: :current_attributes) do |batch|
              batch <<
                "def #{name}=(value)" <<
                "@attributes[:#{name}] = value" <<
                "end"
            end
          end
        end

        self.defaults = defaults.merge(names.index_with { default })
      end

Defined in activesupport/lib/active_support/current_attributes.rb line 115 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::CurrentAttributes

Type at least 2 characters to search.

↑↓ navigate · open · esc close