123456789_123456789_123456789_123456789_123456789_

Module: ActiveModel::Attributes::ClassMethods

Relationships & Source Files
Defined in: activemodel/lib/active_model/attributes.rb

Instance Method Summary

Instance Method Details

#attribute(name, cast_type = nil, default: nil, **options)

Defines a model attribute. In addition to the attribute name, a cast type and default value may be specified, as well as any options supported by the given cast type.

class Person
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :active, :boolean, default: true
end

person = Person.new
person.name = "Volmer"

person.name   # => "Volmer"
person.active # => true
[ GitHub ]

  
# File 'activemodel/lib/active_model/attributes.rb', line 59

def attribute(name, ...)
  super
  define_attribute_method(name)
end

#attribute_names

Returns an array of attribute names as strings.

class Person
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :age, :integer
end

Person.attribute_names # => ["name", "age"]
[ GitHub ]

  
# File 'activemodel/lib/active_model/attributes.rb', line 74

def attribute_names
  attribute_types.keys
end

#define_method_attribute=(canonical_name, owner:, as: canonical_name) (private)

[ GitHub ]

  
# File 'activemodel/lib/active_model/attributes.rb', line 92

def define_method_attribute=(canonical_name, owner:, as: canonical_name)
  ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method(
    owner, canonical_name, writer: true,
  ) do |temp_method_name, attr_name_expr|
    owner.define_cached_method(temp_method_name, as: "#{as}=", namespace: :active_model) do |batch|
      batch <<
        "def #{temp_method_name}(value)" <<
        "  _write_attribute(#{attr_name_expr}, value)" <<
        "end"
    end
  end
end

#type_for_attribute(attribute_name, &block)

Returns the type of the specified attribute after applying any modifiers. This method is the only valid source of information for anything related to the types of a model’s attributes. The return value of this method will implement the interface described by ::ActiveModel::Type::Value (though the object itself may not subclass it).

[ GitHub ]

  
# File 'activemodel/lib/active_model/attributes.rb', line 79

rdoc_method :method: type_for_attribute