-
-
Save resistorsoftware/972340 to your computer and use it in GitHub Desktop.
Hacking ActiveResource::Connection for Shopify API in order to read HTTP response header 'http_x_shopify_api_call_limit'. Simply require this code after your gems have been loaded.
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
class ActiveResource::Connection | |
# HACK 1: Add an attr_reader for response | |
attr_reader :response | |
def request(method, path, *arguments) | |
result = ActiveSupport::Notifications.instrument("request.active_resource") do |payload| | |
payload[:method] = method | |
payload[:request_uri] = "#{site.scheme}://#{site.host}:#{site.port}#{path}" | |
payload[:result] = http.send(method, path, *arguments) | |
end | |
# HACK 2: Save response to instance var @response | |
@response = handle_response(result) | |
rescue Timeout::Error => e | |
raise TimeoutError.new(e.message) | |
rescue OpenSSL::SSL::SSLError => e | |
raise SSLError.new(e.message) | |
end | |
end | |
module ShopifyAPI | |
## | |
# returns a Hash containing current API call count and limit. If no API call has yet been executed, a call to | |
# ShopifyAPI::Shop.current will be executed in order to retrieve a first response. | |
# @return {:count => Integer, :limit => Integer} | |
# | |
def self.call_limit | |
unless ActiveResource::Base.connection.response | |
Shop.current | |
end | |
global = ActiveResource::Base.connection.response['http_x_shopify_api_call_limit'].split('/') | |
local = ActiveResource::Base.connection.response['http_x_shopify_shop_api_call_limit'].split('/') | |
{:global_count => global[0], :global_limit => global[1], :local_count => local[0], :local_limit => local[1]} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment