Sha256: bde72f9f476aba7e648aa29a926a1363b8b3843011a510fee1744962e3c5d8a6

Contents?: true

Size: 1.24 KB

Versions: 4

Compression:

Stored size: 1.24 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={}, &block)
          instantiate_target(:new, attrs, &block)
        end

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

        def create!(attrs={}, &block)
          instantiate_target(:create!, attrs, &block)
        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={}, &block)
          @target = klass.send(instantiator, attrs, &block)
          proxy_owner[association.foreign_key] = @target.id
          loaded
          @target
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mongo_mapper-0.15.1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.15.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.14.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.14.0.rc1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb