Sha256: f54b45c2891c374e0b4fe1850daa8621fc0f7311ef1ea3476df008c5ac21dda1

Contents?: true

Size: 1.53 KB

Versions: 6

Compression:

Stored size: 1.53 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(opts={})
        owner = @owner
        child = @association.klass.new(opts)
        assign_parent_reference(child)
        child._parent_document = owner
        self << child
        child
      end
      
      def find(opts)
        case opts
        when :all
          self
        when String
          if load_target
            child = @target.detect {|item| item.id == opts}
            assign_parent_reference(child)
            child
          end
        end
      end

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

      protected
        def find_target
          (@_values || []).map do |e|
            child = @association.klass.new(e)
            assign_parent_reference(child)
            child
          end
        end
        
      private
      
        def assign_parent_reference(child)
          return unless child && @owner
          return if @owner.class.name.blank?
          owner = @owner
          child.class_eval do
            define_method(owner.class.name.underscore) do
              owner
            end
          end
        end
      
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
hashrocket-mongomapper-0.3.10 lib/mongomapper/associations/many_embedded_proxy.rb
hashrocket-mongomapper-0.3.11 lib/mongomapper/associations/many_embedded_proxy.rb
hashrocket-mongomapper-0.3.12 lib/mongomapper/associations/many_embedded_proxy.rb
hashrocket-mongomapper-0.3.13 lib/mongomapper/associations/many_embedded_proxy.rb
hashrocket-mongomapper-0.3.14 lib/mongomapper/associations/many_embedded_proxy.rb
hashrocket-mongomapper-0.3.15 lib/mongomapper/associations/many_embedded_proxy.rb