Module: Pagy::ElasticsearchRailsPaginator

Defined in:
lib/pagy/toolbox/paginators/elasticsearch_rails.rb

Class Method Summary collapse

Class Method Details

.paginate(search, options) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/pagy/toolbox/paginators/elasticsearch_rails.rb', line 9

def paginate(search, options)
  if search.is_a?(Search::Arguments)  # Active mode

    Searcher.wrap(search, options) do
      model, arguments, search_options = search

      search_options[:size] = options[:limit]
      search_options[:from] = options[:limit] * ((options[:page] || 1) - 1)

      method          = options[:search_method] || ElasticsearchRails::DEFAULT[:search_method]
      response_object = model.send(method, *arguments, **search_options)
      options[:count] = total_count_from(response_object)

      [ElasticsearchRails.new(**options), response_object]
    end

  else # Passive mode
    from, size      = pagination_params_from(search)
    options[:limit] = size
    options[:page]  = ((from || 0) / options[:limit]) + 1
    options[:count] = total_count_from(search)

    ElasticsearchRails.new(**options)
  end
end

.pagination_params_from(response_object) ⇒ Object

Support different versions of ElasticsearchRails



36
37
38
39
40
41
42
43
44
45
# File 'lib/pagy/toolbox/paginators/elasticsearch_rails.rb', line 36

def pagination_params_from(response_object)
  definition = response_object.search.definition
  definition = definition.to_hash if definition.respond_to?(:to_hash)
  container  = (definition.is_a?(Hash) && (definition[:body] || definition)) || response_object.search.options
  from       = (container[:from] || container['from']).to_i
  size       = (container[:size] || container['size']).to_i
  size       = 10 if size.zero?

  [from, size]
end

.total_count_from(response_object) ⇒ Object

Support different versions of ElasticsearchRails



48
49
50
51
52
53
54
# File 'lib/pagy/toolbox/paginators/elasticsearch_rails.rb', line 48

def total_count_from(response_object)
  total = response_object.instance_eval do
            respond_to?(:response) ? response['hits']['total'] : raw_response['hits']['total']
          end

  total.is_a?(Hash) ? total['value'] : total
end