Class: Cloth::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil) ⇒ Client

Returns a new instance of Client.

Raises:

  • (Exception)


7
8
9
10
# File 'lib/cloth/client.rb', line 7

def initialize(api_key = nil)
  @api_key = api_key || Cloth.api_key
  raise Exception, "An API key must be set before the Cloth client can be used. Set an API key with 'Cloth.api_key = ...'" unless @api_key
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



6
7
8
# File 'lib/cloth/client.rb', line 6

def api_key
  @api_key
end

Class Method Details

.get(url, options = {}) ⇒ Object



38
39
40
# File 'lib/cloth/client.rb', line 38

def get(url, options = {})
  Cloth.client.get(url, options)
end

.post(url, options = {}) ⇒ Object



42
43
44
# File 'lib/cloth/client.rb', line 42

def post(url, options = {})
  Cloth.client.post(url, options)
end

Instance Method Details

#get(url, options = {}) ⇒ Object



12
13
14
# File 'lib/cloth/client.rb', line 12

def get(url, options = {})
  JSON.parse(request(:get, url, options).run.body)
end

#post(url, options = {}) ⇒ Object



16
17
18
19
# File 'lib/cloth/client.rb', line 16

def post(url, options = {})
  headers = { 'Content-Type': "application/x-www-form-urlencoded" }
  JSON.parse(request(:post, url, options.merge({ headers: headers })).run.body)
end

#request(method, url, options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/cloth/client.rb', line 21

def request(method, url, options = {})
  fixed_url = url[0] == "/" ? url[1..-1] : url
  url = [Cloth.api_url, fixed_url].join('/')
  Typhoeus::Request.new(
    url,
    method: method,
    body: options[:body],
    params: options[:params],
    headers: {
      'Accept': 'application/json',
      'Cloth-Api-Key': @api_key,
      'Content-Type': 'application/json'
    }.merge(options[:headers] || {})
  )
end