Sha256: 6516ab26d598271498b8be3d4c12a0ea97bd5c27866f5b8b21c34b348f930123

Contents?: true

Size: 1.26 KB

Versions: 6

Compression:

Stored size: 1.26 KB

Contents

# encoding: UTF-8
module MarkMapper
  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

6 entries across 6 versions & 1 rubygems

Version Path
mark_mapper-0.0.6 lib/mark_mapper/plugins/associations/belongs_to_proxy.rb
mark_mapper-0.0.5 lib/mark_mapper/plugins/associations/belongs_to_proxy.rb
mark_mapper-0.0.4 lib/mark_mapper/plugins/associations/belongs_to_proxy.rb
mark_mapper-0.0.3 lib/mark_mapper/plugins/associations/belongs_to_proxy.rb
mark_mapper-0.0.2 lib/mark_mapper/plugins/associations/belongs_to_proxy.rb
mark_mapper-0.0.1 lib/mark_mapper/plugins/associations/belongs_to_proxy.rb