Module: ActiveModel::Attributes

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

Overview

:nodoc:

Defined Under Namespace

Modules: ClassMethods

Constant Summary

Constants included from AttributeMethods

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

Instance Method Summary collapse

Methods included from ActiveSupport::Concern

append_features, class_methods, extended, included

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"]


112
113
114
# File 'activemodel/lib/active_model/attributes.rb', line 112

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::Model
  include ActiveModel::Attributes

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

person = Person.new(name: 'Francesco', age: 22)
person.attributes
# => {"name"=>"Francesco", "age"=>22}


96
97
98
# File 'activemodel/lib/active_model/attributes.rb', line 96

def attributes
  @attributes.to_hash
end

#initializeObject



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

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