I am trying to create an API wrapper for recharge (A Shopify subscription service), I am using the HTTParty gem
module RechargeAPI
require 'httparty'
BASE_URI = 'https://api.rechargeapps.com'
API_TOKEN = 'my_token'
class Client
include HTTParty
base_uri BASE_URI
headers 'X-Recharge-Access-Token': API_TOKEN
end
class Customer < Client
def self.search(params)
response = get('/customers', query: params)
self.from_json(response.body)
end
def self.find(params)
self.search(params).first
end
def self.all
response = get('/customers')
self.from_json(response.body)
end
def self.from_json(customers_json)
customers = JSON.parse(customers_json).dig('customers')
customers.map do|customer| OpenStruct.new(customer)
end
end
end
end
RechargeAPI::Customer.find(shopify_customer_id: 5363543224286) # returns <OpenStruct accepts_marketing=nil, analytics_data={"utm_params"=>[]}, billing_address1=....
It works fine, However i feel i am not using the best practices for writing an api wrapper.
Ideally i would set my api token with something like RechargeAPI.api_token = 'token'
rather than it being hardcoded or in an ENV file. But i dont know how then i would use headers 'X-Recharge-Access-Token': API_TOKEN
Also ideally RechargeAPI::Customer.find(shopify_customer_id: 5363543224863)
would return a RechargeAPI::Customer
object rather than an OpenStruct
. I would love to be able to inherit from Struct
but obviously i cannot as I am inheriting from my RechargeAPI::Client
class.
Could anybody advise on how i could go about doing this, or any way to improve this code. Thankyou!