Sha256: a8974076a7367bf3b82bad8ba596383864d4398a7460db9d1861a02869834607

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

# encoding: UTF-8
module MongoMapper
  module Plugins
    module Associations
      class SingleAssociation < Base
        def setup(model)
          model.associations_module.module_eval <<-end_eval
            def #{name}
              proxy = get_proxy(associations[#{name.inspect}])
              proxy.nil? ? nil : proxy
            end

            def #{name}=(value)
              association = associations[#{name.inspect}]
              proxy = get_proxy(association)

              if proxy.nil? || proxy.target != value
                proxy = build_proxy(association)
              end

              proxy.replace(value)
              value
            end

            def #{name}?
              get_proxy(associations[#{name.inspect}]).present?
            end

            def build_#{name}(attrs={})
              get_proxy(associations[#{name.inspect}]).build(attrs)
            end

            def create_#{name}(attrs={})
              get_proxy(associations[#{name.inspect}]).create(attrs)
            end

            def create_#{name}!(attrs={})
              get_proxy(associations[#{name.inspect}]).create!(attrs)
            end
          end_eval
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mongo_mapper-0.11.0 lib/mongo_mapper/plugins/associations/single_association.rb
mongo_mapper-0.10.1 lib/mongo_mapper/plugins/associations/single_association.rb