Skip to content

Instantly share code, notes, and snippets.

@vilusa
Created August 23, 2021 19:12
Show Gist options
  • Save vilusa/83c1439920845eaf3e912c264102bfeb to your computer and use it in GitHub Desktop.
Save vilusa/83c1439920845eaf3e912c264102bfeb to your computer and use it in GitHub Desktop.
Ruby Faraday Client Base
require 'faraday'
module ActionClient
class Client
attr_reader :status_code, :response, :data
def self.request(method: :get, path:, body: nil)
raise ArgumentError, "#{self.class.name} API Key not provided." if ActionClient.api_key.nil?
# Prepare Request URL
request_url = "#{ActionClient.api_base}/#{path}"
# Run Request
response = Faraday.send(method, request_url) do |req|
req.headers['User-Agent'] = "Ruby Client #{VERSION}"
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
req.headers['apiKey'] = ActionClient.api_key
req.body = body.to_json unless body.nil?
end
# Parse Response
ActionClient::Response.call response
end
end
end
module ActionClient
class Configuration
attr_accessor :api_key
attr_reader :api_base
def initialize
@api_base = "https://api.example.com"
end
def self.setup
new.tap do |instance|
yield(instance) if block_given?
end
end
end
end
module ActionClient
VERSION = "v0.2.1".freeze
@config = ActionClient::Configuration.setup
class << self
extend Forwardable
attr_reader :config
# User configurable option
def_delegators :@config, :api_key, :api_key=
def_delegators :@config, :api_base
end
end
module ActionClient
class Process < Client
OBJECT = "object".freeze
def self.retrieve(id)
response = request path: OBJECT, body: { id: id }
# response.object = ActionClient::ObjectSerializer.new response.data if response.success? # Seriliazer
response
end
def self.create(channel, download, arguments)
request method: :post,
path: OBJECT,
body: { channel: channel, download: download, arguments: arguments }
end
end
end
module ActionClient
class Response
def self.call(response)
object = new(response)
object
end
attr_accessor :object
attr_reader :response, :faraday_response, :data
attr_reader :status_code, :success, :action_success, :error
alias :success? :success
alias :error? :error
alias :action_success? :action_success
def initialize(response)
# Assign Faraday Response Object
@faraday_response = response
# Handle Response Status
@status_code = response.status
@success = status_code >= 200 && status_code < 300
@error = status_code >= 400 && status_code < 600
# Handle Response with status code
@response = success? ? JSON.parse(response.body) : response.body
@data = success? ? @response.dig("data") : nil
@action_success = success? ? @response.dig("success") : false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment