Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save resistorsoftware/973201 to your computer and use it in GitHub Desktop.
Save resistorsoftware/973201 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. Caveat emptor: This hack modifies a private method of AR::Connection; H
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
# Takes form num_requests_executed/max_requests
# Eg: 101/3000
CALL_LIMIT_HEADER_PARAM = 'http_x_shopify_api_call_limit'
class << self
##
# How many more API calls can I make?
#
def available_calls
call_limit - call_count
end
##
# Have I reached my API call limit?
#
def maxed_out?
call_limit == call_count
end
##
# How many total API calls can I make?
# @return Integer
#
def call_limit
@api_call_limit ||= api_call_limit_param.pop.to_i
end
##
# How many API calls have I made?
# @return Integer
def call_count
api_call_limit_param.shift.to_i
end
def api_call_limit_param
response[CALL_LIMIT_HEADER_PARAM].split('/')
end
def response
Shop.current unless ActiveResource::Base.connection.response
ActiveResource::Base.connection.response
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment