Class: WCC::API::RestClient

Inherits:
Object
  • Object
show all
Defined in:
lib/wcc/api/rest_client.rb,
lib/wcc/api/rest_client/response.rb,
lib/wcc/api/rest_client/api_error.rb,
lib/wcc/api/rest_client/http_adapter.rb,
lib/wcc/api/rest_client/typhoeus_adapter.rb

Defined Under Namespace

Classes: AbstractResponse, ApiError, DefaultResponse, HttpAdapter, NotFoundError, TyphoeusAdapter

Constant Summary collapse

ADAPTERS =
{
  http: ['http', '> 1.0', '< 3.0'],
  typhoeus: ['typhoeus', '~> 1.0']
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_url:, headers: nil, **options) ⇒ RestClient

Returns a new instance of RestClient.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/wcc/api/rest_client.rb', line 9

def initialize(api_url:, headers: nil, **options)
  # normalizes a URL to have a slash on the end
  @api_url = api_url.gsub(/\/+$/, '') + '/'

  @adapter = RestClient.load_adapter(options[:adapter])

  @options = options
  @query_defaults = {}
  @headers = {
    'Accept' => 'application/json'
  }.merge(headers || {}).freeze
  @response_class = options[:response_class] || DefaultResponse
end

Instance Attribute Details

#api_urlObject (readonly)

Returns the value of attribute api_url.



7
8
9
# File 'lib/wcc/api/rest_client.rb', line 7

def api_url
  @api_url
end

Class Method Details

.load_adapter(adapter) ⇒ Object

This method is long due to the case statement, not really a better way to do it



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/wcc/api/rest_client.rb', line 41

def self.load_adapter(adapter)
  case adapter
  when nil
    ADAPTERS.each do |a, spec|
      begin
        gem(*spec)
        return load_adapter(a)
      rescue Gem::LoadError
        next
      end
    end
    raise ArgumentError, 'Unable to load adapter!  Please install one of '\
      "#{ADAPTERS.values.map(&:join).join(',')}"
  when :http
    require_relative 'rest_client/http_adapter'
    HttpAdapter.new
  when :typhoeus
    require_relative 'rest_client/typhoeus_adapter'
    TyphoeusAdapter.new
  else
    unless adapter.respond_to?(:call)
      raise ArgumentError, "Adapter #{adapter} is not invokeable!  Please "\
        "pass a proc or use one of #{ADAPTERS.keys}"
    end
    adapter
  end
end

Instance Method Details

#get(path, query = {}) ⇒ Object

performs an HTTP GET request to the specified path within the configured space and environment. Query parameters are merged with the defaults and appended to the request.



26
27
28
29
30
31
32
# File 'lib/wcc/api/rest_client.rb', line 26

def get(path, query = {})
  url = URI.join(@api_url, path)

  @response_class.new(self,
    { url: url, query: query },
    get_http(url, query))
end