Class: Balloon::Http::Response
- Inherits:
-
Object
- Object
- Balloon::Http::Response
- Defined in:
- lib/balloon/http/response.rb
Constant Summary collapse
- CONTENT_TYPE =
{ 'application/json' => :json, 'application/x-www-form-urlencoded' => :html, 'text/html' => :html, 'text/javascript' => :json }
- PARSERS =
{ :json => lambda{ |body| MultiJson.respond_to?(:adapter) ? MultiJson.load(body) : MultiJson.decode(body) rescue body}, :html => lambda{ |body| Nokogiri::HTML(body)} }
Instance Attribute Summary collapse
-
#response ⇒ Object
readonly
Returns the value of attribute response.
Instance Method Summary collapse
- #body ⇒ Object
-
#content_type ⇒ Object
Attempts to determine the content type of the response.
- #decode(body) ⇒ Object
- #headers ⇒ Object
-
#initialize(response) ⇒ Response
constructor
A new instance of Response.
- #json? ⇒ Boolean
- #parsed ⇒ Object
- #parser ⇒ Object
- #status ⇒ Object
Constructor Details
#initialize(response) ⇒ Response
Returns a new instance of Response.
18 19 20 |
# File 'lib/balloon/http/response.rb', line 18 def initialize(response) @response = response end |
Instance Attribute Details
#response ⇒ Object (readonly)
Returns the value of attribute response.
4 5 6 |
# File 'lib/balloon/http/response.rb', line 4 def response @response end |
Instance Method Details
#body ⇒ Object
26 27 28 |
# File 'lib/balloon/http/response.rb', line 26 def body decode(response.body) end |
#content_type ⇒ Object
Attempts to determine the content type of the response.
50 51 52 |
# File 'lib/balloon/http/response.rb', line 50 def content_type ((response.headers.values_at('content-type', 'Content-Type').compact.first || '').split(';').first || '').strip end |
#decode(body) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/balloon/http/response.rb', line 30 def decode(body) return '' if !body return body if json? charset = body.match(/charset\s*=[\s|\W]*([\w-]+)/) if charset[1].downcase != "utf-8" begin body.encode! "utf-8", charset[1], {:invalid => :replace} rescue body end else body end end |
#headers ⇒ Object
22 23 24 |
# File 'lib/balloon/http/response.rb', line 22 def headers response.headers end |
#json? ⇒ Boolean
54 55 56 |
# File 'lib/balloon/http/response.rb', line 54 def json? CONTENT_TYPE[content_type] == :json || !response.body.match(/\<html/) end |
#parsed ⇒ Object
64 65 66 67 68 |
# File 'lib/balloon/http/response.rb', line 64 def parsed return nil unless CONTENT_TYPE.key?(content_type) return nil unless PARSERS.key?(parser) @parsed ||= PARSERS[parser].call(body) end |
#parser ⇒ Object
58 59 60 61 62 |
# File 'lib/balloon/http/response.rb', line 58 def parser type = CONTENT_TYPE[content_type] type = :json if type == :html && !response.body.match(/\<html/) return type end |
#status ⇒ Object
45 46 47 |
# File 'lib/balloon/http/response.rb', line 45 def status response.status end |