Sha256: 739cf9fda7cd571fa0b9c78ddb112f4d4295acfca2b44ab5f96428bfd9142c99

Contents?: true

Size: 1.26 KB

Versions: 4

Compression:

Stored size: 1.26 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.13.1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.13.0 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.13.0.beta2 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
mongo_mapper-0.13.0.beta1 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb