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

Namespace

Module

Methods

Included Modules

Instance Public methods

attribute_names()

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"]
📝 Source code
# File activemodel/lib/active_model/attributes.rb, line 133
    def attribute_names
      @attributes.keys
    end
🔎 See on GitHub

attributes()

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}
📝 Source code
# File activemodel/lib/active_model/attributes.rb, line 118
    def attributes
      @attributes.to_hash
    end
🔎 See on GitHub