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.



15
16
17
18
19
# File 'lib/embeds_many/child_collection.rb', line 15

def initialize(obj, field, child_klass)
  @obj = obj
  @field = field
  @child_klass = child_klass
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



35
36
37
# File 'lib/embeds_many/child_collection.rb', line 35

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

Instance Method Details

#allObject

all records



28
29
30
31
32
# File 'lib/embeds_many/child_collection.rb', line 28

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

#create(attrs = {}) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/embeds_many/child_collection.rb', line 7

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

  record.save

  record
end

#find(id) ⇒ Object



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

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

  attrs && @child_klass.new(attrs.merge(parent: @obj))
end

#new(attrs = {}) ⇒ Object



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

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