Skip to content
Browse files

+ Parses the response body if a parser in defined for it's content-type

  • Loading branch information...
1 parent 329f3dc commit a9886452950790ed2921e8e762cdcdb4dc7baad8 @Dirklectisch Dirklectisch committed Apr 15, 2011
Showing with 88 additions and 1 deletion.
  1. +41 −1 lib/rufus/verbs/endpoint.rb
  2. +47 −0 test/parse_test.rb
View
42 lib/rufus/verbs/endpoint.rb
@@ -68,10 +68,19 @@ class EndPoint
# The endpoint initialization opts (Hash instance)
#
attr_reader :opts
+
+ #
+ # Configure default parsers for this EndPoint, example:
+ # ep.parsers['application/json'] = Yajl::Parser
+ # ep.parsers['application/xhtml+xml'] = Nokogiri::HTML::Document
+ #
+
+ attr_reader :parsers
def initialize (opts)
@opts = opts
+ @parsers = {}
compute_target @opts
@@ -569,9 +578,11 @@ def handle_response (method, res, opts)
#
# following the redirection
end
-
+
decompress res
+ parse_body res
+
res
end
@@ -635,6 +646,35 @@ def body
gz.close
end
end
+
+ #
+ # Parses the response body if a parser in defined for it's content-type
+ #
+
+ def parse_body (res)
+
+ content_type = res.header['content-type']
+
+ if content_parser = self.parsers[content_type]
+
+ class << res
+ attr_accessor :parsed_body
+
+ alias :old_body :body
+
+ def body
+ parsed_body || old_body
+ end
+ end
+
+ res.parsed_body = content_parser.send(:parse, res.body)
+
+ end
+
+ res
+
+ end
+
end
end
end
View
47 test/parse_test.rb
@@ -0,0 +1,47 @@
+
+require File.dirname(__FILE__) + '/base.rb'
+
+class PlainText
+
+ def self.parse text
+ self.new text
+ end
+
+ def initialize text
+ @text = text
+ end
+
+end
+
+class ParseTest < Test::Unit::TestCase
+ include TestBaseMixin
+ include Rufus::Verbs
+
+ # def test_0
+ # ep = EndPoint.new(
+ # :host => "localhost",
+ # :port => 7777,
+ # :headers => {'Accept' => 'text/plain'})
+ #
+ # ep.parsers['text/plain'] = PlainText
+ #
+ # resp = ep.get(:resource => "items")
+ #
+ # assert_equal 'text/plain', resp.header['content-type']
+ # assert_equal PlainText, resp.body.class
+ #
+ # end
+
+ def test_1
+ require 'nokogiri'
+
+ ep = EndPoint.new(:host => 'rufus.rubyforge.org')
+ ep.parsers['text/html'] = Nokogiri::HTML::Document
+
+ res = ep.get
+
+ assert_equal Nokogiri::HTML::Document, res.body.class
+
+ end
+
+end

0 comments on commit a988645

Please sign in to comment.
Something went wrong with that request. Please try again.