class Firstclasspostcodes::Client
Attributes
config[RW]
The Configuration
object holding settings to be used in the API client.
user_agent[R]
The User-agent for the library
Public Class Methods
default()
click to toggle source
# File lib/firstclasspostcodes/client.rb, line 77 def self.default @default ||= Client.new end
new(config = Configuration.default)
click to toggle source
@option config [Configuration] Configuration
for initializing the object
# File lib/firstclasspostcodes/client.rb, line 17 def initialize(config = Configuration.default) @config = config @user_agent = "Firstclasspostcodes/ruby@#{Firstclasspostcodes::VERSION}" on("request") { |req| @config.logger.debug(req) if @config.debug } on("response") { |req| @config.logger.debug(req) if @config.debug } on("error") { |req| @config.logger.error(req) } end
Public Instance Methods
build_request_url(path)
click to toggle source
# File lib/firstclasspostcodes/client.rb, line 71 def build_request_url(path) # Add leading and trailing slashes to path path = "/#{path}".gsub(%r{/+}, "/") @config.base_url + path end
call_request(*args)
click to toggle source
# File lib/firstclasspostcodes/client.rb, line 49 def call_request(*args) response = Typhoeus::Request.new(*args).run return response if response.success? raise handle_request_error(response) end
handle_request_error(response)
click to toggle source
# File lib/firstclasspostcodes/client.rb, line 57 def handle_request_error(response) raise ResponseError.new("Connection timed out", "timeout") if response.timed_out? raise ResponseError.new(response.return_message, "liberror") if response.code == 0 error = begin JSON.parse(response.body, symbolize_names: true) rescue JSON::ParserError response.body end raise ResponseError.new(error, "network-error") end
request(opts)
click to toggle source
# File lib/firstclasspostcodes/client.rb, line 25 def request(opts) url = build_request_url(opts[:path]) request_params = { params: opts[:query_params] || {}, method: opts[:method].to_sym.downcase, } request_params.merge!(@config.to_request_params) emit("request", request_params) response = call_request(url, request_params) data = JSON.parse(response.body, symbolize_names: true) emit("response", data) data rescue ResponseError => e emit("error", e) raise e end