Created
May 18, 2011 14:57
-
-
Save christocracy/978745 to your computer and use it in GitHub Desktop.
Redefine #find_every to stitch together large Shopify queries where count > 250 into multiple calls.
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
# Example usage | |
begin | |
rs = ShopifyAPI::Order.all | |
rescue ShopifyAPI::Limits::Error | |
# Not enough credits to execute this request. Queue to DJ here, perhaps?? | |
end | |
## | |
# Redefines #find_every to automatically compose resultsets from multiple ShopifyAPI queries due to API limit of 250 records / request. | |
# Seemlessly stitches all requests to #all, #find(:all), etc, as if there were no LIMIT. | |
# @see http://wiki.shopify.com/Retrieving_more_than_250_Products%2C_Orders_etc. | |
# | |
module ActiveResource | |
class Base | |
QUERY_LIMIT = 250 | |
class << self | |
# get reference to unbound class-method #find_every | |
find_every = self.instance_method(:find_every) | |
define_method(:find_every) do |options| | |
options[:params] ||= {} | |
pages = (count(options)/QUERY_LIMIT).ceil | |
raise ShopifyAPI::Limits::Error.new unless ShopifyAPI.credits_left >= pages | |
rs = [] | |
# Iterate from 1 -> max-pages and call the original #find_every, capturing the responses into one list | |
1.upto(pages) {|page| | |
options[:params][:page] = page | |
rs.concat find_every.bind(self).call(options) | |
} | |
rs | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment