Module: Tremendous::Request

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



9
10
11
# File 'lib/tremendous/request.rb', line 9

def access_token
  @access_token
end

#uriObject (readonly)

Returns the value of attribute uri.



9
10
11
# File 'lib/tremendous/request.rb', line 9

def uri
  @uri
end

Instance Method Details

#_execute(method, url, data = {}, *opts) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/tremendous/request.rb', line 27

def _execute(method, url, data={}, *opts)
  data[:format] = :json
  data[:headers] = {
    'authorization' => "Bearer #{@access_token}"
  }.merge(data.class == Hash ? data[:headers] || {} : {})

  HTTParty.send(method, url, data, *opts)
end

#delete(path, data = {}, *opts) ⇒ Object



23
24
25
# File 'lib/tremendous/request.rb', line 23

def delete(path, data={}, *opts)
  handle_response(_execute(:delete, url(path), data, *opts))
end

#get(path, data = {}, *opts) ⇒ Object



11
12
13
# File 'lib/tremendous/request.rb', line 11

def get(path, data={}, *opts)
  handle_response(_execute(:get, url(path), data, *opts))
end

#handle_response(response) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/tremendous/request.rb', line 40

def handle_response(response)
  if response.success?
    response_json = JSON.parse(response.body).with_indifferent_access
  else
    case response.code
    when 400
      raise Tremendous::BadDataError.new(response)
    when 401
      raise Tremendous::AccessError.new(response)
    when 402
      raise Tremendous::PaymentError.new(response)
    else
      raise Tremendous::Error.new(response)
    end
  end
end

#initialize(access_token, uri) ⇒ Object



4
5
6
7
# File 'lib/tremendous/request.rb', line 4

def initialize(access_token, uri)
  @access_token = access_token
  @uri = uri
end

#post(path, data = {}, *opts) ⇒ Object



15
16
17
# File 'lib/tremendous/request.rb', line 15

def post(path, data={}, *opts)
  handle_response(_execute(:post, url(path), data, *opts))
end

#put(path, data = {}, *opts) ⇒ Object



19
20
21
# File 'lib/tremendous/request.rb', line 19

def put(path, data={}, *opts)
  handle_response(_execute(:put, url(path), data, *opts))
end

#url(path, params = {}) ⇒ Object



36
37
38
# File 'lib/tremendous/request.rb', line 36

def url(path, params={})
  URI.join(uri, path)
end