Class: PipeLineDealer::Collection::Concerns::ResultsFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/pipe_line_dealer/collection/concerns/results_fetcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, options) ⇒ ResultsFetcher

Returns a new instance of ResultsFetcher.



7
8
9
10
# File 'lib/pipe_line_dealer/collection/concerns/results_fetcher.rb', line 7

def initialize(collection, options)
  @collection = collection
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/pipe_line_dealer/collection/concerns/results_fetcher.rb', line 5

def options
  @options
end

Instance Method Details

#each(&block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/pipe_line_dealer/collection/concerns/results_fetcher.rb', line 16

def each &block
  @params =  { page: 1, per_page: PipeLineDealer::Limits::MAX_RESULTS_PER_PAGE }

  @results_yielded = 0

  # Enforce maximum number of resulst per page.
  if limit && limit > PipeLineDealer::Limits::MAX_RESULTS_PER_PAGE
    options[:limit] = PipeLineDealer::Limits::MAX_RESULTS_PER_PAGE
  end

  @params[:per_page] = limit

  #TODO: refactor this deal specific piece of code.
  if options.has_key?(:where) && options[:where].has_key?(:query) && options[:where][:query].has_key?(:company_id)
    @params[:company_id] = options[:where][:query][:company_id].to_s
  end

  catch :stop_yielding do
    while true
      status, result = @collection.client.connection.get(@collection.collection_url + ".json", @params)

      if status == 200
        yield_results(result, &block)
      else # status != 200
        #TODO
        raise "Unexpected status #{status.inspect}"
      end
    end
  end
end

#limitObject



12
13
14
# File 'lib/pipe_line_dealer/collection/concerns/results_fetcher.rb', line 12

def limit
  options[:limit] || PipeLineDealer::Limits::MAX_RESULTS_PER_PAGE
end

#yield_results(result, &block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/pipe_line_dealer/collection/concerns/results_fetcher.rb', line 47

def yield_results result, &block
  result["entries"].each do |entry|
    block.call(@collection.klass.new(collection: @collection, persisted: true, attributes: entry))
    @results_yielded += 1

    throw :stop_yielding if @results_yielded >= limit
  end

  if result["pagination"]["page"] < result["pagination"]["pages"]
    @params[:page] += 1
  else
    throw :stop_yielding
  end
end