lib/recurly/pager.rb in recurly-3.4.1 vs lib/recurly/pager.rb in recurly-3.5.0
- old
+ new
@@ -5,13 +5,31 @@
def initialize(client:, path:, options: {})
@client = client
@path = path
@options = map_array_params(options)
- @next = build_path(@path, @options)
+ rewind!
end
+ # Performs a request with the pager `limit` set to 1 and only returns the first
+ # result in the response.
+ def first
+ # Modify the @next url to set the :limit to 1
+ original_next = @next
+ @next = @path
+ fetch_next!(@options.merge(limit: 1))
+ # Restore the @next url to the original
+ @next = original_next
+ @data.first
+ end
+
+ # Makes a HEAD request to the API to determine how many total records exist.
+ def count
+ resource = @client.send(:head, self.next, @options)
+ resource.get_response.total_records
+ end
+
# Enumerates each "page" from the server.
# This method yields a given block with the array of items
# in the page `data` and the page number the pagination is on
# `page_num` which is 0-indexed.
#
@@ -82,46 +100,47 @@
end
def page_enumerator
Enumerator.new do |yielder|
loop do
- fetch_next!
+ # Pass in @options when requesting the first page (@data.empty?)
+ next_options = @data.empty? ? @options : {}
+ fetch_next!(next_options)
yielder << data
unless has_more?
rewind!
break
end
end
end
end
- def fetch_next!
- page = @client.next_page(self)
+ def fetch_next!(options)
+ path = extract_path(self.next)
+ page = @client.send(:get, path, options)
@data = page.data.map { |d| JSONParser.from_json(d) }
@has_more = page.has_more
@next = page.next
end
def rewind!
@data = []
- @next = build_path(@path, @options)
+ @next = @path
end
- def build_path(path, options)
- if options.empty?
- path
- else
- "#{path}?#{URI.encode_www_form(options)}"
- end
+ # Returns just the path and parameters so we can safely reuse the connection
+ def extract_path(uri_or_path)
+ uri = URI(uri_or_path)
+ uri.kind_of?(URI::HTTP) ? uri.request_uri : uri_or_path
end
# Converts array parameters to CSV strings to maintain consistency with
# how the server expects the request to be formatted while providing the
# developer with an array type to maintain developer happiness!
def map_array_params(params)
@options = params.map do |key, param|
new_param = param.is_a?(Array) ? param.join(",") : param
[key, new_param]
- end
+ end.to_h
end
end
end