Class: ResponseCollection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ResponseCollection

seed_page, total, per_page, load_more_call



10
11
12
13
14
15
16
# File 'lib/bright/response_collection.rb', line 10

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]
end

Instance Attribute Details

#load_more_callObject

Returns the value of attribute load_more_call.



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

def load_more_call
  @load_more_call
end

#paged_objectsObject

Returns the value of attribute paged_objects.



4
5
6
# File 'lib/bright/response_collection.rb', line 4

def paged_objects
  @paged_objects
end

#per_pageObject

Returns the value of attribute per_page.



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

def per_page
  @per_page
end

#totalObject Also known as: size, length

Returns the value of attribute total.



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

def total
  @total
end

Instance Method Details

#eachObject



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

def each
  current_page = -1
  while (current_page += 1) < @pages do
    objects = [@paged_objects[current_page]].flatten.compact
    next_page_no = current_page + 1
    if load_more_call and @paged_objects[next_page_no].nil? and next_page_no < @pages
      next_page_thread = Thread.new do
        load_more_call.call(next_page_no)
      end
    else
      next_page_thread = nil
    end
    objects.each do |obj|
      yield obj
    end
    @paged_objects[next_page_no] = next_page_thread.value if next_page_thread
  end
end

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  total <= 0
end

#lastObject



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

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



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

def loaded_results
  @paged_objects.values.flatten
end