Class: AlPapi::Http
- Inherits:
-
Object
- Object
- AlPapi::Http
- Defined in:
- lib/al_papi/http.rb
Instance Attribute Summary collapse
-
#config ⇒ Object
Returns the value of attribute config.
-
#errors ⇒ Object
Returns the value of attribute errors.
-
#response ⇒ Object
Returns the value of attribute response.
-
#success ⇒ Object
Returns the value of attribute success.
Instance Method Summary collapse
- #build_params(params = nil) ⇒ Object
- #get(path, params = {}) ⇒ Object
-
#initialize(_config) ⇒ Http
constructor
A new instance of Http.
- #post(path, params = {}) ⇒ Object
- #request(http_verb, path, params = nil) ⇒ Object
Constructor Details
#initialize(_config) ⇒ Http
Returns a new instance of Http.
7 8 9 |
# File 'lib/al_papi/http.rb', line 7 def initialize(_config) @config, @errors, @success = _config, [], false end |
Instance Attribute Details
#config ⇒ Object
Returns the value of attribute config.
5 6 7 |
# File 'lib/al_papi/http.rb', line 5 def config @config end |
#errors ⇒ Object
Returns the value of attribute errors.
5 6 7 |
# File 'lib/al_papi/http.rb', line 5 def errors @errors end |
#response ⇒ Object
Returns the value of attribute response.
5 6 7 |
# File 'lib/al_papi/http.rb', line 5 def response @response end |
#success ⇒ Object
Returns the value of attribute success.
5 6 7 |
# File 'lib/al_papi/http.rb', line 5 def success @success end |
Instance Method Details
#build_params(params = nil) ⇒ Object
19 20 21 22 23 |
# File 'lib/al_papi/http.rb', line 19 def build_params(params = nil) return nil if params.empty? return nil unless params.is_a?(Hash) params.merge(auth_token: @config.api_key, format: 'json') end |
#get(path, params = {}) ⇒ Object
11 12 13 |
# File 'lib/al_papi/http.rb', line 11 def get(path, params = {}) request 'get', "#{path}?#{RestClient::Payload.generate(build_params(params))}" end |
#post(path, params = {}) ⇒ Object
15 16 17 |
# File 'lib/al_papi/http.rb', line 15 def post(path, params = {}) request 'post', path, build_params(params) end |
#request(http_verb, path, params = nil) ⇒ Object
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 |
# File 'lib/al_papi/http.rb', line 25 def request(http_verb, path, params = nil) url = "#{@config.host}#{path}" args = http_verb == 'post' ? [http_verb, url, params] : [http_verb, url] response = RestClient.send *args do |res, req, raw_res| body = raw_res.body code = raw_res.code.to_i self.response = body self.errors = [] case code when 200 begin parsed = JSON.parse body rescue JSON::ParserError => e self.response = body end self.success = true when 204 self.errors << RequestError.new('No Content', code, path, params) when 401 self.errors << RequestError.new('Invalid Auth Token Provided', code, path, params) else self.errors << RequestError.new(body, code, path, params) end Response.new(self, code, path, params) end end |