Class: ColaClient

Inherits:
Object
  • Object
show all
Defined in:
lib/cola_client.rb

Constant Summary collapse

MEDIA_TYPES =
[:form, :json]
METHODS =
[:get, :post, :patch, :put, :delete]
CONTENT_TYPE_HEADER =
'Content-Type'

Class Method Summary collapse

Class Method Details

.go(method, url, query: nil, body: nil, headers: {}, options: {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cola_client.rb', line 13

def self.go(method, url, query: nil, body: nil, headers: {}, options: {}) 
  uri = URI(url)
  uri.query = URI.encode_www_form(query) if query

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true if uri.scheme.match(/^https/)

  payload = nil

  if body
    case options[:content_type]
    when :form
      payload = URI.encode_www_form body
      headers[CONTENT_TYPE_HEADER] = 'application/x-www-form-urlencoded'
    when :json
      payload = body.to_json
      headers[CONTENT_TYPE_HEADER] = 'application/json'
    else
      headers[CONTENT_TYPE_HEADER] = 'text/plain'
      payload = body.to_s
    end
  end

  if options[:basic_auth]
    headers.merge! basic_auth options[:basic_auth]
  end

  response = http.send_request(method.to_s.upcase, uri.request_uri, payload, headers)

  if options[:accept] == :json
    response.body = JSON.parse(response.body, symbolize_names: true) unless response.body.empty?
  end

  response
end

.method_missing(method, *args) ⇒ Object



49
50
51
52
53
54
# File 'lib/cola_client.rb', line 49

def self.method_missing method, *args
  if METHODS.include? method.to_sym
    args.unshift method.to_sym
    self.send :go, *args
  end    
end