Sha256: 8b81f4b7598d2a1f98d900edcda15b6480ff3cd1f109b8e6b4127f7e829f686a

Contents?: true

Size: 1.79 KB

Versions: 5

Compression:

Stored size: 1.79 KB

Contents

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

      def many(association_id, options = {})
        create_association(:many, association_id, options)        
        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
          define_association_methods(association)
          define_association_keys(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
        
        def define_association_keys(association)
          if association.belongs_to?
            key(association.belongs_to_key_name, String)
            key(association.type_key_name, String) if association.polymorphic?            
          end
          
          if association.many? && association.polymorphic?
            association.klass.send(:key, association.type_key_name, String)
          end
        end
    end

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

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
djsun-mongomapper-0.3.1.1 lib/mongomapper/associations.rb
djsun-mongomapper-0.3.1 lib/mongomapper/associations.rb
jnunemaker-mongomapper-0.3.0 lib/mongomapper/associations.rb
jnunemaker-mongomapper-0.3.1 lib/mongomapper/associations.rb
jnunemaker-mongomapper-0.3.2 lib/mongomapper/associations.rb