我通常使用法拉第gem连接到外部API,但我想为我的纯Ruby应用程序尝试HTTParty。我的想法是构建灵活的客户端类,类似于made with Faraday中的这个类:
class Client
API_ENDPOINT = 'https://id.amiqus.co/api/'
PERSONAL_ACCESS_TOKEN = ENV['personal_access_token']
def initialize
@access_token = PERSONAL_ACCESS_TOKEN
end
def get(path, options = {})
client.public_send(:get, path.to_s, options)
end
private
def client
@client =
Faraday.new(API_ENDPOINT) do |client|
client.request :url_encoded
client.response :json, content_type: /\bjson$/
client.adapter Faraday.default_adapter
client.headers['Accept'] = 'application/json'
client.headers['Content-Type'] = 'application/json'
client.headers['Authorization'] = "Bearer #{access_token}" if access_token.present?
end
end
如何使用HTTParty构建记忆client
方法?
1条答案
按热度按时间sqxo8psd1#