Class: Oshpark::Connection
- Inherits:
-
Object
- Object
- Oshpark::Connection
- Defined in:
- lib/oshpark/connection.rb
Instance Method Summary collapse
-
#initialize(endpoint_url) ⇒ Connection
constructor
A new instance of Connection.
- #request(method, endpoint, params = {}, token) ⇒ Object
Constructor Details
#initialize(endpoint_url) ⇒ Connection
Returns a new instance of Connection.
14 15 16 |
# File 'lib/oshpark/connection.rb', line 14 def initialize endpoint_url self.api_endpoint = endpoint_url end |
Instance Method Details
#request(method, endpoint, params = {}, token) ⇒ Object
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/oshpark/connection.rb', line 18 def request method, endpoint, params={}, token method = method[0].upcase + method[1..-1] uri = uri_for endpoint http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.port == 443 request = Net::HTTP.const_get(method).new(uri.path) default_headers(token).each do |header, value| request[header] = value end if params.keys.include? :file boundary = MicroToken.generate 20 request.body = "--#{boundary}\r\n" + params.to_multipart.join('--' + boundary + "\r\n") + "--#{boundary}--\r\n" request['Content-Type'] = "multipart/form-data; boundary=#{boundary}" else request.body = params.to_query end response = http.request(request) json = if response.body.size >= 2 JSON.parse(response.body) else {} end case response.code.to_i when 401 raise Unauthorized, json['error'] when 404 raise NotFound, json['error'] when 422 raise Unprocessable, json['error'] when 400...499 raise HttpError, json['error'] when 500...599 raise ServerError, json['error'] end json rescue JSON::ParserError => e raise ServerError, "Bad response from server: #{e.}" end |