Sha256: 30567665e8144079cb76c9d3c6c2036f0fe2452580f67e90643cbc4880996e81

Contents?: true

Size: 1.19 KB

Versions: 4

Compression:

Stored size: 1.19 KB

Contents

module MongoMapper
  module Associations
    class ManyEmbeddedProxy < Proxy
      def replace(v)
        @_values = v.map { |e| e.kind_of?(EmbeddedDocument) ? e.attributes : e }
        reset
      end

      def build(attributes={})
        doc = @association.klass.new(attributes)
        assign_root_document(doc)
        self << doc
        doc
      end

      # TODO: test that both string and oid version work
      def find(id)
        load_target
        @target.detect { |item| item.id == id || item._id == id }
      end

      def <<(*docs)
        if load_target
          docs.each do |doc|
            assign_root_document(doc)
            @target << doc
          end
        end
      end
      alias_method :push, :<<
      alias_method :concat, :<<

      private
        def find_target
          (@_values || []).map do |e|
            child = @association.klass.new(e)
            assign_root_document(child)
            child
          end
        end

        def root_document
          @owner._root_document || @owner
        end

        def assign_root_document(*docs)
          docs.each do |doc|
            doc._root_document = root_document
          end
        end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
mongo_mapper-0.6.2 lib/mongo_mapper/associations/many_embedded_proxy.rb
mongo_mapper-0.6.1 lib/mongo_mapper/associations/many_embedded_proxy.rb
mongo_mapper-unstable-2009.11.18 lib/mongo_mapper/associations/many_embedded_proxy.rb
mongo_mapper-0.6.0 lib/mongo_mapper/associations/many_embedded_proxy.rb