Class: Goldpricez::Request

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

Defined Under Namespace

Classes: GoldpricezError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, path, token = nil) ⇒ Request

Returns a new instance of Request.



9
10
11
12
13
# File 'lib/goldpricez/request.rb', line 9

def initialize(host, path, token=nil)
  @token = token
  @path = path
  @session = Faraday.new url: host
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



7
8
9
# File 'lib/goldpricez/request.rb', line 7

def path
  @path
end

#sessionObject

Returns the value of attribute session.



7
8
9
# File 'lib/goldpricez/request.rb', line 7

def session
  @session
end

#tokenObject

Returns the value of attribute token.



7
8
9
# File 'lib/goldpricez/request.rb', line 7

def token
  @token
end

Instance Method Details

#cast_error(response) ⇒ Object

Raises:



25
26
27
28
29
30
31
32
33
# File 'lib/goldpricez/request.rb', line 25

def cast_error(response)
  error_map = {
    500 => 'Sever error! Something were wrong in the server.',
    400 => "Bad request!, #{ message }",
    404 => 'Not found!',
    405 => 'Operation does not allowed!',
  }
  raise GoldpricezError, "Status: #{ response.status }. Error: #{ error_map[response.status] }"
end

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



15
16
17
18
19
20
21
22
23
# File 'lib/goldpricez/request.rb', line 15

def get(url, params={})
    params = JSON.generate(params)
    response = @session.get do |req|
      req.url "#{ @path }#{ url }"
      req.headers['X-API-KEY'] = @token
    end
    cast_error(response) unless (response.status == 200 || response.status == 201)
    return JSON JSON.parse(response.body, :quirks_mode => true)
end