Module: ActiveRecord::Embedded::Model::Attributes

Extended by:
ActiveSupport::Concern
Included in:
ActiveRecord::Embedded::Model
Defined in:
lib/active_record/embedded/model/attributes.rb

Overview

Functionality for storing and casting attributes on an embedded model. Uses the configured fields for the given model to cast/coerce attributes into and out of (respectively) the database.

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

Read an attribute from the model.

Parameters:

  • key (Symbol)
    • Attribute name

Returns:

  • (Object)

    Coerced value of this attribute, or nil if it cannot be found.


26
27
28
29
30
31
32
# File 'lib/active_record/embedded/model/attributes.rb', line 26

def [](key)
  value = attributes[key.to_sym]

  return if value.nil?

  coerce(key, value)
end

#[]=(key, value) ⇒ Object

Write an attribute to the model.

Parameters:

  • key (Symbol)
    • Attribute name

  • value (Object)
    • Value of this attribute


38
39
40
# File 'lib/active_record/embedded/model/attributes.rb', line 38

def []=(key, value)
  attributes[key.to_sym] = cast(key, value)
end

#assign_attributes(attrs = {}) ⇒ Hash

Cast attributes before assignment using ActiveModel::AttributeMethods.

Parameters:

  • attrs (Hash) (defaults to: {})
    • Attributes to assign

Returns:

  • (Hash)

    casted attributes


66
67
68
# File 'lib/active_record/embedded/model/attributes.rb', line 66

def assign_attributes(attrs = {})
  super cast_attributes(attrs)
end

#inspectString

Returns:

  • (String)

48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/active_record/embedded/model/attributes.rb', line 48

def inspect
  inspection = if @attributes
                 self.class.field_names.collect do |name|
                   if has_attribute?(name)
                     "#{name}: #{attribute_for_inspect(name)}"
                   end
                 end.compact.join(', ')
               else
                 'not initialized'
               end
  "#<#{self.class} #{inspection}>"
end

#key?(key) ⇒ Boolean

Whether the given attribute exists on this model.

Returns:


43
44
45
# File 'lib/active_record/embedded/model/attributes.rb', line 43

def key?(key)
  attributes.key?(key.to_sym)
end