Sha256: 4e6af239f6af4401fcd3074e3442af832545ff13291076d82d384a94a246d154

Contents?: true

Size: 1.53 KB

Versions: 8

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

require 'active_record'

module Esse
  module Plugins
    module ActiveRecord
      module RepositoryClassMethods
        # @param [Class] model_class The ActiveRecord Relation or model class
        # @param [Hash] options The options
        # @option options [Symbol] :batch_size The batch size for the collection
        def collection(*args, **kwargs, &block)
          unless model_or_relation?(args.first)
            return super(*args, **kwargs, &block)
          end
          model_class = args.shift

          repo = Class.new(Esse::ActiveRecord::Collection)
          repo.base_scope = -> { model_class }
          repo.batch_size = kwargs.delete(:batch_size) if kwargs.key?(:batch_size)
          repo.class_eval(&block) if block

          super(repo, *args, **kwargs)
        end

        def dataset(**params)
          if @collection_proc.nil?
            raise NotImplementedError, "Can't call `dataset' on a repository without a collection defined"
          elsif @collection_proc.is_a?(Class) && @collection_proc < Esse::ActiveRecord::Collection
            @collection_proc.new(**params).dataset
          elsif defined? super
            super
          else
            raise NoMethodError, "undefined method `dataset' for #{self}"
          end
        end

        private

        def model_or_relation?(klass)
          return true if klass.is_a?(Class) && klass < ::ActiveRecord::Base
          return true if klass.is_a?(::ActiveRecord::Relation)

          false
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
esse-active_record-0.3.4 lib/esse/plugins/active_record.rb
esse-active_record-0.3.3 lib/esse/plugins/active_record.rb
esse-active_record-0.3.2 lib/esse/plugins/active_record.rb
esse-active_record-0.3.1 lib/esse/plugins/active_record.rb
esse-active_record-0.3.0 lib/esse/plugins/active_record.rb
esse-active_record-0.2.1 lib/esse/plugins/active_record.rb
esse-active_record-0.2.0 lib/esse/plugins/active_record.rb
esse-active_record-0.1.1 lib/esse/plugins/active_record.rb