Class: AnyApi::Request

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

Constant Summary collapse

HTTPMETHODS =
["Get", "Head", "Post", "Patch", "Put", "Proppatch", "Lock", "Unlock", "Options", "Propfind", "Delete", "Move", "Copy", "Mkcol", "Trace"]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_method, endpoint, params_hsh = nil) ⇒ Request

Returns a new instance of Request.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/any_api.rb', line 15

def initialize(http_method, endpoint, params_hsh = nil)

  uri = URI.parse("#{AnyApi.configuration.api_base_url}/#{endpoint}")

  res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    # a safe eval as only  one of the above HTTPMETHODS would be allowed ie: Get, Put, Post, Delete
    request = eval "Net::HTTP::#{http_method if HTTPMETHODS.include?(http_method)}.new uri"
    request.basic_auth(AnyApi.configuration.username, AnyApi.configuration.password)
    request["Content-Type"] = "application/json"
    if params_hsh
      request.body = params_hsh.to_json
    end
    http.request request
  end

  @apiresult = res
end

Instance Attribute Details

#apiresultObject

Returns the value of attribute apiresult.



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

def apiresult
  @apiresult
end

Instance Method Details

#is_ok?Boolean

Returns:

  • (Boolean)


48
49
50
51
52
53
54
55
56
# File 'lib/any_api.rb', line 48

def is_ok?
  case  apiresult
  when Net::HTTPSuccess
    true
  else
    false
  end

end

#parser_responseObject



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/any_api.rb', line 34

def parser_response
  case  apiresult
    when Net::HTTPSuccess
      JSON.parse  apiresult.body
    when Net::HTTPUnauthorized
      {'error' => "#{ apiresult.message}: username and password set and correct?"}
    when Net::HTTPServerError
      {'error' => "#{ apiresult.message}: try again later?"}
    else
      {'error' =>  "there seems to be an error in the server, please try again"}
  end
end