Sha256: 4f602984a94f3c6ee4f82440a93b1fedfbc2ea0a7a274c434160747f6f70749e

Contents?: true

Size: 1.22 KB

Versions: 3

Compression:

Stored size: 1.22 KB

Contents

module Services
  class BaseFinder < Services::Base
    disable_call_logging

    def call(ids = [], conditions = {})
      ids, conditions = Array(ids), conditions.symbolize_keys
      special_conditions = conditions.extract!(:order, :limit, :page, :per_page)

      object_table_id = "#{object_class.table_name}.id"

      scope = object_class.public_send(Rails::VERSION::MAJOR == 3 ? :scoped : :all)
      scope = scope.where(object_table_id => ids) unless ids.empty?

      unless conditions.empty?
        scope = scope
          .select("DISTINCT #{object_table_id}")
          .order(object_table_id)
        scope = process(scope, conditions)
        scope = object_class.where(id: scope)
      end

      special_conditions.each do |k, v|
        case k
        when :order
          order = if v == 'random'
            'RANDOM()'
          else
            "#{object_class.table_name}.#{v}"
          end
          scope = scope.order(order)
        when :limit
          scope = scope.limit(v)
        when :page
          scope = scope.page(v)
        when :per_page
          scope = scope.per(v)
        else
          raise ArgumentError, "Unexpected special condition: #{k}"
        end
      end

      scope
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
services-2.2.3 lib/services/base_finder.rb
services-2.1.0 lib/services/base_finder.rb
services-2.0.2 lib/services/base_finder.rb