Sha256: a31c726db9c919e170a1a7bf72988e43ef696d57db17a2cb0c4b4471dd0cc0b5

Contents?: true

Size: 1.98 KB

Versions: 7

Compression:

Stored size: 1.98 KB

Contents

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

      def many(association_id, options={}, &extension)
        create_association(:many, association_id, options, &extension)
        self
      end
      
      def associations
        @associations ||= HashWithIndifferentAccess.new
      end
      
      def associations=(hash)
        @associations = hash
      end
      
      def inherited(subclass)
        subclass.associations = associations.dup
        super
      end

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

          define_method("#{association.name}=") do |value|
            get_proxy(association).replace(value)
            value
          end
          
          if association.options[:dependent] && association.many? && !association.embeddable?
            after_destroy do |doc|
              case association.options[:dependent]
                when :destroy
                  doc.get_proxy(association).destroy_all
                when :delete_all
                  doc.get_proxy(association).delete_all
                when :nullify
                  doc.get_proxy(association).nullify
              end
            end
          end
        end
    end
    
    module InstanceMethods
      def associations
        self.class.associations
      end

      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) if !frozen?
        end
        proxy
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 3 rubygems

Version Path
tpitale-mongo_mapper-0.6.9 lib/mongo_mapper/associations.rb
mongo_mapper-unstable-2009.12.30 lib/mongo_mapper/associations.rb
mongo_mapper-unstable-2009.12.29 lib/mongo_mapper/associations.rb
mongo_mapper-unstable-2009.12.23 lib/mongo_mapper/associations.rb
mongo_mapper-unstable-2009.12.22 lib/mongo_mapper/associations.rb
mongo_mapper-unstable-2009.12.16 lib/mongo_mapper/associations.rb
mongo_mapper-0.6.8 lib/mongo_mapper/associations.rb