Sha256: 3c0138495ec0a21ed3bade751ee7463196af863ea9340ed4ce72d27f875f54ad

Contents?: true

Size: 1.74 KB

Versions: 9

Compression:

Stored size: 1.74 KB

Contents

module MongoMapper
  module Associations
    module ClassMethods
      def belongs_to(association_id, options = {})
        association = create_association(:belongs_to, association_id, options)

        ref_id = "#{association_id}_id"
        key ref_id, String

        define_method("#{ref_id}=") do |value|
          write_attribute(ref_id, value)
        end

        if options[:polymorphic]
          ref_type = "#{association_id}_type"
          key ref_type, String

          define_method("#{ref_type}=") do |value|
            write_attribute(ref_type, value)
          end
        end

        define_association_methods(association)

        self
      end

      def many(association_id, options = {})
        association = create_association(:many, association_id, options)
        define_association_methods(association)

        self
      end

      def associations
        @associations ||= HashWithIndifferentAccess.new
      end

      private
      def create_association(type, name, options)
        association = Associations::Base.new(type, name, options)
        associations[association.name] = association
        association
      end

      def define_association_methods(association)
        define_method(association.name) do
          get_proxy(association)
        end

        define_method("#{association.name}=") do |value|
          get_proxy(association).replace(value)
          value
        end
      end
    end

    module InstanceMethods
      def get_proxy(association)
        proxy = self.instance_variable_get(association.ivar)
        if proxy.nil?
          proxy = association.proxy_class.new(self, association)
          self.instance_variable_set(association.ivar, proxy)
        end
        proxy
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 4 rubygems

Version Path
crnixon-mongomapper-0.2.0 lib/mongomapper/associations.rb
fcoury-mongomapper-0.2.0 lib/mongomapper/associations.rb
fcoury-mongomapper-0.3.0 lib/mongomapper/associations.rb
fcoury-mongomapper-0.3.1 lib/mongomapper/associations.rb
fcoury-mongomapper-0.3.3 lib/mongomapper/associations.rb
fcoury-mongomapper-0.3.4 lib/mongomapper/associations.rb
fcoury-mongomapper-0.3.5 lib/mongomapper/associations.rb
jnunemaker-mongomapper-0.2.0 lib/mongomapper/associations.rb
ramsingla-mongomapper-0.2.1 lib/mongomapper/associations.rb