Class: EmbedsMany::ChildrenCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/embeds_many/child_collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(obj, field, child_klass) ⇒ ChildrenCollection

Returns a new instance of ChildrenCollection.



20
21
22
23
24
25
# File 'lib/embeds_many/child_collection.rb', line 20

def initialize(obj, field, child_klass)
  @obj = obj
  @field = field
  @child_klass = child_klass
  @created_instances = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args, &block) ⇒ Object

pass unhandled message to children array



56
57
58
# File 'lib/embeds_many/child_collection.rb', line 56

def method_missing(symbol, *args, &block)
  all.send(symbol, *args, &block)
end

Instance Method Details

#allObject

all records



39
40
41
42
43
# File 'lib/embeds_many/child_collection.rb', line 39

def all
  @obj.read_attribute(@field).map do |attrs|
    @child_klass.new(attrs.merge(parent: @obj))
  end
end

#before_parent_saveObject

called before parent save



46
47
48
# File 'lib/embeds_many/child_collection.rb', line 46

def before_parent_save
  @created_instances.map(&:before_parent_save)
end

#child_destroyed(child) ⇒ Object

child destroyed



51
52
53
# File 'lib/embeds_many/child_collection.rb', line 51

def child_destroyed(child)
  @created_instances.delete(child)
end

#create(attrs = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/embeds_many/child_collection.rb', line 10

def create(attrs={})
  record = @child_klass.new(attrs.merge(parent: @obj))

  record.save

  @created_instances << record

  record
end

#find(id) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/embeds_many/child_collection.rb', line 27

def find(id)
  attrs = @obj.read_attribute(@field).find {|child| child['id'].to_i == id.to_i }

  if attrs
    record = @child_klass.new(attrs.merge(parent: @obj))
    @created_instances << record

    record
  end
end

#new(attrs = {}) ⇒ Object



3
4
5
6
7
8
# File 'lib/embeds_many/child_collection.rb', line 3

def new(attrs={})
  record = @child_klass.new(attrs.merge(parent: @obj))
  @created_instances << record

  record
end