module ActiveModel::Attributes
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
Public Instance Methods
attribute_names()
click to toggle source
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"]
# File lib/active_model/attributes.rb, line 146 def attribute_names @attributes.keys end
attributes()
click to toggle source
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}
# File lib/active_model/attributes.rb, line 131 def attributes @attributes.to_hash end
Private Instance Methods
_write_attribute(attr_name, value)
click to toggle source
# File lib/active_model/attributes.rb, line 156 def _write_attribute(attr_name, value) @attributes.write_from_user(attr_name, value) end
Also aliased as: attribute=
attribute(attr_name)
click to toggle source
# File lib/active_model/attributes.rb, line 161 def attribute(attr_name) @attributes.fetch_value(attr_name) end