Module: ActiveModel::Attributes

Extended by:
ActiveSupport::Concern
Includes:
AttributeMethods, AttributeRegistration
Defined in:
lib/active_model/attributes.rb

Overview

Active Model Attributes

The Attributes module allows models to define attributes beyond simple Ruby readers and writers. Similar to Active Record attributes, which are typically inferred from the database schema, Active Model Attributes are aware of data types, can have default values, and can handle casting and serialization.

To use Attributes, include the module in your model class and define your attributes using the attribute macro. It accepts a name, a type, a default value, and any other options supported by the attribute type.

Examples

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

Defined Under Namespace

Modules: ClassMethods

Constant Summary

Constants included from AttributeMethods

ActiveModel::AttributeMethods::CALL_COMPILABLE_REGEXP, ActiveModel::AttributeMethods::FORWARD_PARAMETERS, ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP

Instance Method Summary collapse

Methods included from AttributeMethods

#attribute_missing, #method_missing, #respond_to?, #respond_to_without_attributes?

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class ActiveModel::AttributeMethods

Instance Method Details

#attribute_namesObject

Returns an array of attribute names as strings.

class Person
  include ActiveModel::Attributes

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

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


133
134
135
# File 'lib/active_model/attributes.rb', line 133

def attribute_names
  @attributes.keys
end

#attributesObject

Returns a hash of all the attributes with their names as keys and the values of the attributes as values.

class Person
  include ActiveModel::Attributes

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

person = Person.new
person.name = "Francesco"
person.age = 22

person.attributes # => { "name" => "Francesco", "age" => 22}


118
119
120
# File 'lib/active_model/attributes.rb', line 118

def attributes
  @attributes.to_hash
end

#freezeObject

:nodoc:



137
138
139
140
# File 'lib/active_model/attributes.rb', line 137

def freeze # :nodoc:
  @attributes = @attributes.clone.freeze unless frozen?
  super
end

#initializeObject

:nodoc:



93
94
95
96
# File 'lib/active_model/attributes.rb', line 93

def initialize(*) # :nodoc:
  @attributes = self.class._default_attributes.deep_dup
  super
end

#initialize_dup(other) ⇒ Object

:nodoc:



98
99
100
101
# File 'lib/active_model/attributes.rb', line 98

def initialize_dup(other) # :nodoc:
  @attributes = @attributes.deep_dup
  super
end