Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge remote branch 'dirk/parsing'

  • Loading branch information...
commit 090445e7d6dcbd334c4b0155cad2c4e8a03b991f 2 parents ecca4a2 + a988645
@jmettraux jmettraux authored
View
2  CHANGELOG.txt
@@ -4,6 +4,8 @@
== rufus-verbs - 1.0.0 not yet released
+- Parses the response body if a parser in defined for its content-type (Dirk Geurs)
+- EndPoint params merge with Request params (Dirk Geurs)
- todo : upgraded to Rakefile, thanks Kenneth Kalmer
- bug : poor escaping of parameters (URI -> CGI) fixed, thanks nmaisonneuve
View
6 CREDITS.txt
@@ -1,6 +1,12 @@
= CREDITS.txt
+
+== contributors
+
+Dirk Geurs - https://github.com/Dirklectisch
+
+
== Feedback
Nicolas Maisonneuve : http://github.com/nmaisonneuve
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
@@ -577,9 +586,11 @@ def handle_response (method, res, opts)
#
# following the redirection
end
-
+
decompress res
+ parse_body res
+
res
end
@@ -643,6 +654,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
Please sign in to comment.
Something went wrong with that request. Please try again.