Class: Wordnik::Response
- Extended by:
- ActiveModel::Naming
- Includes:
- ActiveModel::Conversion, ActiveModel::Validations
- Defined in:
- lib/wordnik/response.rb
Instance Attribute Summary collapse
-
#raw ⇒ Object
Returns the value of attribute raw.
Instance Method Summary collapse
-
#body ⇒ Object
If body is JSON, parse it TODO: If body is XML, parse it Otherwise return raw string.
- #code ⇒ Object
- #error_message ⇒ Object
-
#format ⇒ Object
Extract the response format from the header hash e.g.
- #headers ⇒ Object
-
#initialize(raw) ⇒ Response
constructor
A new instance of Response.
- #json? ⇒ Boolean
-
#persisted? ⇒ Boolean
It’s an ActiveModel thing..
- #pretty_body ⇒ Object
- #pretty_headers ⇒ Object
- #xml? ⇒ Boolean
Constructor Details
#initialize(raw) ⇒ Response
Returns a new instance of Response.
16 17 18 19 20 21 22 23 |
# File 'lib/wordnik/response.rb', line 16 def initialize(raw) self.raw = raw case self.code when 500..510 then raise(ServerError, self.) when 299..426 then raise(ClientError, self.) end end |
Instance Attribute Details
#raw ⇒ Object
Returns the value of attribute raw.
12 13 14 |
# File 'lib/wordnik/response.rb', line 12 def raw @raw end |
Instance Method Details
#body ⇒ Object
If body is JSON, parse it TODO: If body is XML, parse it Otherwise return raw string
38 39 40 41 42 |
# File 'lib/wordnik/response.rb', line 38 def body JSON.parse raw.body rescue raw.body end |
#code ⇒ Object
25 26 27 |
# File 'lib/wordnik/response.rb', line 25 def code raw.code end |
#error_message ⇒ Object
29 30 31 32 33 |
# File 'lib/wordnik/response.rb', line 29 def body['message'] rescue body end |
#format ⇒ Object
Extract the response format from the header hash e.g. => ‘application/json’
52 53 54 |
# File 'lib/wordnik/response.rb', line 52 def format headers['Content-Type'].split("/").last.to_s end |
#headers ⇒ Object
44 45 46 47 48 |
# File 'lib/wordnik/response.rb', line 44 def headers h = {} raw.headers_hash.each {|k,v| h[k] = v } h end |
#json? ⇒ Boolean
56 57 58 |
# File 'lib/wordnik/response.rb', line 56 def json? format == 'json' end |
#persisted? ⇒ Boolean
It’s an ActiveModel thing..
82 83 84 |
# File 'lib/wordnik/response.rb', line 82 def persisted? false end |
#pretty_body ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/wordnik/response.rb', line 64 def pretty_body return unless body.present? case format when 'json' JSON.pretty_generate(body).gsub(/\n/, '<br/>') when 'xml' xsl = Nokogiri::XSLT(File.open(File.join(File.dirname(__FILE__), "../../config/pretty_print.xsl"))) xml = Nokogiri(body) coder = HTMLEntities.new coder.encode(xsl.apply_to(xml).to_s) end end |
#pretty_headers ⇒ Object
77 78 79 |
# File 'lib/wordnik/response.rb', line 77 def pretty_headers JSON.pretty_generate(headers).gsub(/\n/, '<br/>') end |
#xml? ⇒ Boolean
60 61 62 |
# File 'lib/wordnik/response.rb', line 60 def xml? format == 'xml' end |