Class: JsonRecord::EmbeddedDocumentArray

Inherits:
Array
  • Object
show all
Defined in:
lib/json_record/embedded_document_array.rb

Overview

This is an array of EmbeddedDocument objects. All elments of the array must be of the same class and all belong to the same parent. If an array of hashes are passed in, they will all be converted to EmbeddedDocument objects of the class specified.

Instance Method Summary collapse

Constructor Details

#initialize(klass, parent, objects = []) ⇒ EmbeddedDocumentArray

Returns a new instance of EmbeddedDocumentArray.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/json_record/embedded_document_array.rb', line 6

def initialize (klass, parent, objects = [])
  @klass = klass
  @parent = parent
  objects = [] unless objects
  objects = [objects] unless objects.is_a?(Array)
  objects = objects.collect do |obj|
    obj = @klass.new(obj) if obj.is_a?(Hash)
    if obj.is_a?(@klass)
      obj.parent = parent
      obj
    else
      raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
    end
  end
  super(objects)
end

Instance Method Details

#<<(obj) ⇒ Object

Append an object to the array. The object must either be an EmbeddedDocument of the correct class, or a Hash.

Raises:

  • (ArgumentError)


25
26
27
28
29
30
# File 'lib/json_record/embedded_document_array.rb', line 25

def << (obj)
  obj = @klass.new(obj) if obj.is_a?(Hash)
  raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
  obj.parent = @parent
  super(obj)
end

#build(obj) ⇒ Object

Similar add an EmbeddedDocument to the array and return the object. If the object passed in is a Hash, it will be used to make a new EmbeddedDocument.

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
# File 'lib/json_record/embedded_document_array.rb', line 46

def build (obj)
  obj = @klass.new(obj) if obj.is_a?(Hash)
  raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
  obj.parent = @parent
  self << obj
  obj
end

#concat(objects) ⇒ Object

Concatenate an array of objects to the array. The objects must either be an EmbeddedDocument of the correct class, or a Hash.



34
35
36
37
38
39
40
41
42
# File 'lib/json_record/embedded_document_array.rb', line 34

def concat (objects)
  objects = objects.collect do |obj|
    obj = @klass.new(obj) if obj.is_a?(Hash)
    raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
    obj.parent = @parent
    obj
  end
  super(objects)
end