Class: ResponseCollection

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/bright/response_collection.rb

Direct Known Subclasses

CursorResponseCollection

Constant Summary collapse

DEFAULT_NO_THREADS =
4

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ResponseCollection

seed_page, total, per_page, load_more_call



14
15
16
17
18
19
20
21
# File 'lib/bright/response_collection.rb', line 14

def initialize(options = {})
  @paged_objects = {0 => options[:seed_page]}
  @total = options[:total].to_i
  @per_page = options[:per_page].to_i
  @pages = (@per_page > 0) ? (@total.to_f / @per_page.to_f).ceil : 0
  @load_more_call = options[:load_more_call]
  @no_threads = options[:no_threads] || DEFAULT_NO_THREADS
end

Instance Attribute Details

#load_more_callObject

Returns the value of attribute load_more_call.



9
10
11
# File 'lib/bright/response_collection.rb', line 9

def load_more_call
  @load_more_call
end

#paged_objectsObject

Returns the value of attribute paged_objects.



6
7
8
# File 'lib/bright/response_collection.rb', line 6

def paged_objects
  @paged_objects
end

#per_pageObject

Returns the value of attribute per_page.



8
9
10
# File 'lib/bright/response_collection.rb', line 8

def per_page
  @per_page
end

#totalObject Also known as: size, length

Returns the value of attribute total.



7
8
9
# File 'lib/bright/response_collection.rb', line 7

def total
  @total
end

Instance Method Details

#eachObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/bright/response_collection.rb', line 23

def each
  Parallel.each(0..@pages, in_threads: @no_threads) do |current_page|
    objects = if @paged_objects[current_page].present?
      @paged_objects[current_page]
    else
      load_more_call.call(current_page)
    end
    objects = [objects].flatten.compact
    @paged_objects[current_page] = objects if objects.present?
    objects.each do |obj|
      yield obj
    end
  end
end

#empty?Boolean



53
54
55
# File 'lib/bright/response_collection.rb', line 53

def empty?
  total <= 0
end

#lastObject



38
39
40
41
42
43
44
# File 'lib/bright/response_collection.rb', line 38

def last
  last_page_no = @pages - 1
  if load_more_call and (last_page = @paged_objects[last_page_no]).nil?
    last_page = @paged_objects[last_page_no] = load_more_call.call(last_page_no)
  end
  last_page.last
end

#loaded_resultsObject



46
47
48
# File 'lib/bright/response_collection.rb', line 46

def loaded_results
  @paged_objects.values.flatten
end