Created
April 15, 2017 20:12
-
-
Save iloveitaly/59240b21903d28e6f1ad39d5ba84e729 to your computer and use it in GitHub Desktop.
Add pagination to Shopify's ruby client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# NOTE pairs well with API request limit backoff | |
# https://gist.github.com/iloveitaly/cf0566bd598732c1e81bad0de1be4ff7 | |
# https://github.com/Shopify/shopify_api/pull/339 | |
ShopifyAPI::Base.class_eval do | |
def self.list(params = {}) | |
find(:all, params: params) | |
end | |
def self.auto_paging_each(opts = {}) | |
opts[:limit] ||= 50 | |
page_limit = opts[:limit] | |
total_count = self.count(opts) | |
pages = total_count/page_limit + 1 | |
current_page = opts[:page] || 0 | |
records = [] | |
while current_page != pages | |
self.list(opts.merge(page: current_page)).each do |record| | |
records << record | |
yield(record) if block_given? | |
end | |
# TODO should keep incrementing until no results are returned instead of | |
# relying on the page count when the requests were initiated | |
current_page += 1 | |
end | |
records | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment