Sha256: cea3c2c506e406a21926c31efc5b35b944d69a1487a90d50d5d8b3ca8b16ae13

Contents?: true

Size: 1.09 KB

Versions: 4

Compression:

Stored size: 1.09 KB

Contents

module MongoModel
  module Associations
    extend ActiveSupport::Concern
    
    def associations
      @_associations ||= self.class.associations.inject({}) do |result, (name, association)|
        result[name] = association.for(self)
        result
      end
    end
    
    module ClassMethods
      def belongs_to(name, options={})
        associations[name] = create_association(BelongsTo, name, options)
      end
      
      def has_many(name, options={})
        associations[name] = create_association(has_many_type(options), name, options)
      end
    
      def associations
        read_inheritable_attribute(:associations) || write_inheritable_attribute(:associations, {})
      end
    
    private
      def has_many_type(options)
        case options[:by]
        when :ids
          HasManyByIds
        when :foreign_key
          HasManyByForeignKey
        else
          ancestors.include?(Document) ? HasManyByForeignKey : HasManyByIds
        end
      end
      
      def create_association(type, name, options={})
        type.new(self, name, options).define!
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mongomodel-0.3.3 lib/mongomodel/concerns/associations.rb
mongomodel-0.3.2 lib/mongomodel/concerns/associations.rb
mongomodel-0.3.1 lib/mongomodel/concerns/associations.rb
mongomodel-0.3.0 lib/mongomodel/concerns/associations.rb