Sha256: 1f7d111b4e81103eb4ba15a786e68a2cfdd606c812009ef014a2da68ea04c01f

Contents?: true

Size: 1.2 KB

Versions: 11

Compression:

Stored size: 1.2 KB

Contents

# encoding: UTF-8
module MongoMapper
  module Plugins
    module Associations
      class BelongsToProxy < Proxy
        def replace(doc)
          if doc
            doc.save if !doc.persisted?
            id = doc.id
          end

          reset
          proxy_owner[association.foreign_key] = id
          unless doc.nil?
            loaded
            @target = doc
          end
          @target
        end

        def build(attrs={})
          instantiate_target(:new, attrs)
        end

        def create(attrs={})
          instantiate_target(:create, attrs)
        end

        def create!(attrs={})
          instantiate_target(:create!, attrs)
        end

        def save_to_collection(options={})
          @target.save(options) if @target
        end

        protected
          def find_target
            return nil if proxy_owner[association.foreign_key].nil?
            klass.find_by_id(proxy_owner[association.foreign_key])
          end

          def instantiate_target(instantiator, attrs={})
            @target = klass.send(instantiator, attrs)
            proxy_owner[association.foreign_key] = @target.id
            loaded
            @target
          end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 3 rubygems

Version Path
mongo_mapper-0.12.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
lookout-mongo_mapper-0.11.3 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.11.2 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
jamieorc-mongo_mapper-0.11.1.1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.11.1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.11.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.10.1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.10.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.9.2 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.9.1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.9.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb