Sha256: e0469057d67865fa60801e0adf3b5288b9e2a3b1ee28817016288a373ee32a68

Contents?: true

Size: 1.44 KB

Versions: 6

Compression:

Stored size: 1.44 KB

Contents

module Dase
  class Preloader < ::ActiveRecord::Associations::Preloader

    # custom preloaders for different association types

    class HasMany < ::ActiveRecord::Associations::Preloader::HasMany
      include Dase::PreloaderMethods
    end

    # Not fully implemented yet
    class HasManyThrough < ::ActiveRecord::Associations::Preloader::HasManyThrough
      include Dase::PreloaderMethods

      def foreign_key
        "#{reflection.active_record.table_name}.#{reflection.active_record_primary_key}"
      end

      def records_for(ids)
        reflection.active_record.joins(reflection.name).
            where(foreign_key => ids)
      end
    end

    attr_reader :options

    def initialize(options)
      @options = options
    end

    # an overloaded version of ActiveRecord::Associations::Preloader's preloader_for
    # which returns a class of a custom preloader for a given association
    def preloader_for(reflection, owners, rhs_klass)
      return NullPreloader unless rhs_klass

      if owners.first.association(reflection.name).loaded?
        return AlreadyLoaded
      end

      case reflection.macro
        when :has_many
          reflection.options[:through] ? HasManyThrough : HasMany
        when :has_one, :belongs_to
          raise ArgumentError, "You can't use includes_count_of with a #{reflection.macro} association"
        else
          raise NotImplementedError, "#{reflection.macro} not supported"
      end
    end
  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
dase-5.0.0 lib/dase/preloader.rb
dase-5.1.0 lib/dase/preloader.rb
dase-4.2.1 lib/dase/preloader.rb
dase-4.2.0 lib/dase/preloader.rb
dase-4.1.1 lib/dase/preloader.rb
dase-4.1.0 lib/dase/preloader.rb