Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Adding custom parsers. One failing spec right now.

  • Loading branch information...
commit 2b6ca2f45c413871ed81d7c1e72f0855cb359ad0 1 parent 87b9729
@jnunemaker authored
View
10 lib/httparty.rb
@@ -110,6 +110,16 @@ def format(f)
default_options[:format] = f
end
+ # Allows setting a custom parser for the response.
+ #
+ # class Foo
+ # include HTTParty
+ # parser Proc.new {|data| ...}
+ # end
+ def parser(customer_parser)
+ default_options[:parser] = customer_parser
+ end
+
# Allows making a get request to a url.
#
# class Foo
View
31 lib/httparty/parsers.rb
@@ -0,0 +1,31 @@
+module HTTParty
+ module Xml
+ def self.parse(body)
+ Crack::XML.parse(body)
+ end
+ end
+
+ module Json
+ def self.parse(body)
+ Crack::JSON.parse(body)
+ end
+ end
+
+ module Yaml
+ def self.parse(str)
+ ::YAML.load(str)
+ end
+ end
+
+ module Html
+ def self.parse(str)
+ str
+ end
+ end
+
+ module Text
+ def self.parse(str)
+ str
+ end
+ end
+end
View
25 lib/httparty/request.rb
@@ -107,20 +107,29 @@ def handle_response(response)
end
end
+ # HTTParty.const_get((self.format.to_s || 'text').capitalize)
def parse_response(body)
return nil if body.nil? or body.empty?
- case format
- when :xml
- Crack::XML.parse(body)
- when :json
- Crack::JSON.parse(body)
- when :yaml
- YAML::load(body)
+ if options[:parser].blank?
+ case format
+ when :xml
+ Crack::XML.parse(body)
+ when :json
+ Crack::JSON.parse(body)
+ when :yaml
+ YAML::load(body)
+ else
+ body
+ end
+ else
+ if options[:parser].is_a?(Proc)
+ options[:parser].call(body)
else
body
end
+ end
end
-
+
def capture_cookies(response)
return unless response['Set-Cookie']
cookies_hash = HTTParty::CookieHash.new()
View
22 spec/httparty_spec.rb
@@ -1,5 +1,11 @@
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
+class CustomParser
+ def self.parse(body)
+ return {:sexy => true}
+ end
+end
+
describe HTTParty do
before(:each) do
@klass = Class.new
@@ -174,6 +180,22 @@ def second_method
end
end
+ describe "parser" do
+ before(:each) do
+ @klass.parser Proc.new{ |data| CustomParser.parse(data) }
+ end
+
+ it "should set parser options" do
+ @klass.default_options[:parser].class.should == Proc
+ end
+
+ it "should be able parse response with custom parser" do
+ stub_http_response_with 'twitter.xml'
+ custom_parsed_response = @klass.get('http://twitter.com/statuses/public_timeline.xml')
+ custom_parsed_response[:sexy].should == true
+ end
+ end
+
describe "format" do
it "should allow xml" do
@klass.format :xml
Please sign in to comment.
Something went wrong with that request. Please try again.