Class: Pandarus::RemoteCollection
- Inherits:
-
Object
- Object
- Pandarus::RemoteCollection
- Includes:
- Enumerable
- Defined in:
- lib/pandarus/remote_collection.rb
Instance Method Summary collapse
- #each ⇒ Object
- #each_page ⇒ Object
- #first_page ⇒ Object
- #handle_response(response) ⇒ Object
-
#initialize(http_client, target_class, path, query_params) ⇒ RemoteCollection
constructor
A new instance of RemoteCollection.
- #next_page ⇒ Object
- #to_a ⇒ Object
- #was_last_page? ⇒ Boolean
Constructor Details
#initialize(http_client, target_class, path, query_params) ⇒ RemoteCollection
Returns a new instance of RemoteCollection.
5 6 7 8 9 10 11 12 |
# File 'lib/pandarus/remote_collection.rb', line 5 def initialize(http_client, target_class, path, query_params) @http_client = http_client @target_class = target_class @path = path @query_params = query_params @pagination_links = [] end |
Instance Method Details
#each ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/pandarus/remote_collection.rb', line 18 def each if block_given? each_page do |page| page.each do |member| yield(member) end end else self.to_enum end end |
#each_page ⇒ Object
30 31 32 33 34 35 36 37 |
# File 'lib/pandarus/remote_collection.rb', line 30 def each_page if block_given? yield first_page yield next_page until was_last_page? else self.to_enum end end |
#first_page ⇒ Object
39 40 41 42 43 44 45 |
# File 'lib/pandarus/remote_collection.rb', line 39 def first_page response = @http_client.get do |request| request.path = join_paths(base_path, @path) request.params = request.params.merge(@query_params) unless @query_params.empty? end handle_response(response) end |
#handle_response(response) ⇒ Object
55 56 57 58 59 60 |
# File 'lib/pandarus/remote_collection.rb', line 55 def handle_response(response) unless @pagination_links.any? {|links| links == response.env[:pagination_links] } @pagination_links << response.env[:pagination_links] end response.body.map{|member| @target_class.new(member) } end |
#next_page ⇒ Object
47 48 49 |
# File 'lib/pandarus/remote_collection.rb', line 47 def next_page handle_response @http_client.get(@pagination_links.last.next) end |
#to_a ⇒ Object
14 15 16 |
# File 'lib/pandarus/remote_collection.rb', line 14 def to_a each_page.entries.flatten(1) end |
#was_last_page? ⇒ Boolean
51 52 53 |
# File 'lib/pandarus/remote_collection.rb', line 51 def was_last_page? @pagination_links.last.last_page? end |