Class: Tpaga::Swagger::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/tpaga/swagger/response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw) ⇒ Response

Returns a new instance of Response.



8
9
10
11
12
13
14
15
# File 'lib/tpaga/swagger/response.rb', line 8

def initialize(raw)
  self.raw = raw

  case self.code
  when 500..510 then raise(ServerError, self.error_message)
  when 299..426 then raise(ClientError, self.error_message)
  end
end

Instance Attribute Details

#rawObject

Returns the value of attribute raw.



6
7
8
# File 'lib/tpaga/swagger/response.rb', line 6

def raw
  @raw
end

Instance Method Details

#bodyObject

If body is JSON, parse it Otherwise return raw string



28
29
30
31
32
# File 'lib/tpaga/swagger/response.rb', line 28

def body
  JSON.parse(raw.body, :symbolize_names => true)
rescue
  raw.body
end

#codeObject



17
18
19
# File 'lib/tpaga/swagger/response.rb', line 17

def code
  raw.code
end

#error_messageObject

Account for error messages that take different forms…



22
23
24
# File 'lib/tpaga/swagger/response.rb', line 22

def error_message
  {status: self.code, body: body}.to_json
end

#formatObject

Extract the response format from the header hash e.g. => ‘application/json’



44
45
46
# File 'lib/tpaga/swagger/response.rb', line 44

def format
  headers['Content-Type'].split("/").last.downcase
end

#headersObject

‘headers_hash` is a Typhoeus-specific extension of Hash, so simplify it back into a regular old Hash.



36
37
38
39
40
# File 'lib/tpaga/swagger/response.rb', line 36

def headers
  h = {}
  raw.headers_hash.each {|k,v| h[k] = v }
  h
end

#json?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/tpaga/swagger/response.rb', line 48

def json?
  format == 'json'
end

#pretty_bodyObject



56
57
58
59
60
61
# File 'lib/tpaga/swagger/response.rb', line 56

def pretty_body
  return unless body.present?
  case format
  when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
  end
end

#pretty_headersObject



63
64
65
# File 'lib/tpaga/swagger/response.rb', line 63

def pretty_headers
  JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end

#xml?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/tpaga/swagger/response.rb', line 52

def xml?
  format == 'xml'
end