Class: DynamodbRecord::HasManyCollection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/dynamodb_record/has_many_collection.rb

Overview

Dynamodb::ManyToManyCollection is a class that represent a ManyToManyCollection

Instance Method Summary collapse

Constructor Details

#initialize(pager, base_object) ⇒ HasManyCollection

Returns a new instance of HasManyCollection.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/dynamodb_record/has_many_collection.rb', line 8

def initialize(pager, base_object)
  @base_object = base_object
  @pager = pager
  @klass = @pager.klass
  @options = @pager.options
  @foreign_key = @options[:expression_attribute_values].transform_keys { |k| k.delete_prefix(':').to_sym }
  @items = []
  @pager.items.each do |object|
    @items << @klass.send(:from_database, object)
  end
end

Instance Method Details

#<<(pluralizable_object) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/dynamodb_record/has_many_collection.rb', line 50

def <<(pluralizable_object)
  pluralizable_object = [pluralizable_object] unless pluralizable_object.is_a?(Array)

  pluralizable_object.each do |object|
    res = @items.none? { |data| data.id == object.id }

    next unless res

    foreign_attribute = "#{@base_object.class.to_s.downcase}_id="
    object.send(foreign_attribute, @base_object.id)
    object.save!

    @items << object
  end

  @items
end

#create!(params = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/dynamodb_record/has_many_collection.rb', line 40

def create!(params = {})
  raise "#{@base_object.class} must be saved" if @base_object.new_record

  params.merge!(@foreign_key)
  object = @klass.send(:from_database, params)
  object.save!
  @items << object
  object
end

#eachObject



20
21
22
# File 'lib/dynamodb_record/has_many_collection.rb', line 20

def each(&)
  @items.each(&)
end

#last_evaluated_keyObject



24
25
26
# File 'lib/dynamodb_record/has_many_collection.rb', line 24

def last_evaluated_key
  @pager.last_evaluated_key
end

#next_pageObject



32
33
34
# File 'lib/dynamodb_record/has_many_collection.rb', line 32

def next_page
  self.class.new(@pager.next_page, @base_object)
end

#next_page?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/dynamodb_record/has_many_collection.rb', line 28

def next_page?
  @pager ? @pager.next_page? : false
end

#page(last_key) ⇒ Object



36
37
38
# File 'lib/dynamodb_record/has_many_collection.rb', line 36

def page(last_key)
  self.class.new(@pager.next_page(last_key), @base_object) if last_key
end