Module: ActiveItem::Embeddable

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/active_item/embeddable.rb

Overview

Mixin for models that are stored embedded within a parent record rather than in their own DynamoDB table.

Usage:

class Thing < ActiveItem::Base
self.embedded = true
attr_accessor :name, :weight
end

Embedded models:

  • Cannot be queried directly (no table)
  • Cannot call find, where, all, count, etc.
  • Are serialized/deserialized by their parent
  • Still support validations, callbacks, and dirty tracking

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_embedded_hash(klass, hash) ⇒ Object

Hydrate an embedded record from a DynamoDB hash.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/active_item/embeddable.rb', line 56

def self.from_embedded_hash(klass, hash)
  record = klass.allocate
  record.instance_variable_set(:@id, hash['id'])
  record.instance_variable_set(:@new_record, false)
  record.instance_variable_set(:@created_at, hash['createdAt'])
  record.instance_variable_set(:@updated_at, hash['updatedAt'])

  klass.attribute_names.each do |attr_name|
    next if %w[id dbrecord].include?(attr_name)

    value = nil
    found = false
    klass.dynamo_key_variants(attr_name).each do |key|
      next unless hash.key?(key)

      value = hash[key]
      found = true
      break
    end

    record.instance_variable_set("@#{attr_name}", value) if found
  end

  record.send(:clear_changes_information) if record.respond_to?(:clear_changes_information, true)
  record
end

Instance Method Details

#to_embedded_hashObject

Serialize this embedded record to a DynamoDB-compatible hash.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/active_item/embeddable.rb', line 37

def to_embedded_hash
  item = { 'id' => id || SecureRandom.uuid }

  self.class.attribute_names.each do |attr_name|
    next if %w[id dbrecord].include?(attr_name)

    value = instance_variable_get("@#{attr_name}")
    next if value.nil?

    dynamo_key = self.class.to_dynamo_key(attr_name)
    item[dynamo_key] = value
  end

  item['createdAt'] = @created_at if @created_at
  item['updatedAt'] = @updated_at if @updated_at
  item
end