Sha256: 4ea1fc4a5a8d979c693199b1e7ae3b4cef727792243c5387a6dd98b135c1e391

Contents?: true

Size: 1.94 KB

Versions: 10

Compression:

Stored size: 1.94 KB

Contents

module JsonRecord
  # 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.
  class EmbeddedDocumentArray < Array
    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
    
    # Append an object to the array. The object must either be an EmbeddedDocument of the
    # correct class, or a Hash.
    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
    
    # Concatenate an array of objects to the array. The objects must either be an EmbeddedDocument of the
    # correct class, or a Hash.
    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
    
    # 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.
    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
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
json_record-1.0.8 lib/json_record/embedded_document_array.rb
json_record-1.1.0.b2 lib/json_record/embedded_document_array.rb
json_record-1.0.7 lib/json_record/embedded_document_array.rb
json_record-1.0.6 lib/json_record/embedded_document_array.rb
json_record-1.0.5 lib/json_record/embedded_document_array.rb
json_record-1.0.4 lib/json_record/embedded_document_array.rb
json_record-1.0.3 lib/json_record/embedded_document_array.rb
json_record-1.0.2 lib/json_record/embedded_document_array.rb
json_record-1.0.1 lib/json_record/embedded_document_array.rb
json_record-1.0.0 lib/json_record/embedded_document_array.rb