1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00

Adding custom parsers. One failing spec right now.

This commit is contained in:
John Nunemaker 2009-09-08 23:34:21 -04:00
parent 87b9729b66
commit 2b6ca2f45c
4 changed files with 80 additions and 8 deletions

View file

@ -110,6 +110,16 @@ module HTTParty
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

31
lib/httparty/parsers.rb Normal file
View file

@ -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 file

@ -107,20 +107,29 @@ module HTTParty
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 file

@ -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 @@ describe HTTParty do
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