class Supai::API
Constants
- DEFAULT_HOST
Public Class Methods
new(host = DEFAULT_HOST)
click to toggle source
# File lib/supai/api.rb, line 45 def initialize(host = DEFAULT_HOST) host ||= DEFAULT_HOST # in case we are given nil @host = sanitize_host(host) end
Public Instance Methods
request(method, endpoint, body: nil, params: {}, headers: {}, token: nil)
click to toggle source
# File lib/supai/api.rb, line 56 def request(method, endpoint, body: nil, params: {}, headers: {}, token: nil) uri = build_uri(endpoint, params) http_start(uri) { |http| http.request( build_request( method, uri, body: body, headers: headers, token: token, ) ) } end
sanitize_host(host)
click to toggle source
# File lib/supai/api.rb, line 50 def sanitize_host(host) host = host.split("://", 2).last host = host[0..-2] if host.end_with?("/") host end
Private Instance Methods
build_request(method, uri, body: nil, headers: {}, token: nil)
click to toggle source
# File lib/supai/api.rb, line 88 def build_request(method, uri, body: nil, headers: {}, token: nil) method_class = case method when :get Net::HTTP::Get when :post Net::HTTP::Post end method_class.new(uri.request_uri).tap { |r| headers.each do |key, value| r[key] = value end unless token.nil? r["Authorization"] = token end if body.is_a? String r.body = body elsif !body.nil? r["Content-Type"] = "application/json" r.body = body.to_json end } end
build_uri(endpoint, params = nil)
click to toggle source
# File lib/supai/api.rb, line 73 def build_uri(endpoint, params = nil) URI.parse("https://#{@host}#{endpoint}").tap { |uri| next if params.nil? || params.empty? # munge date/times to iso8601 format params.each do |k, v| if v.respond_to?(:iso8601) params[k] = v.iso8601 end end uri.query = URI.encode_www_form(params) } end
http_opts()
click to toggle source
# File lib/supai/api.rb, line 116 def http_opts { use_ssl: true } end
http_start(uri, &block)
click to toggle source
# File lib/supai/api.rb, line 112 def http_start(uri, &block) Response.new(Net::HTTP.start(uri.host, uri.port, http_opts, &block)) end