Skip to content

Commit

Permalink
Nestled json and xml parsing in parsers
Browse files Browse the repository at this point in the history
  • Loading branch information
jnunemaker committed Jan 31, 2009
1 parent ef61a4a commit 9aa7c84
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 132 deletions.
3 changes: 1 addition & 2 deletions lib/httparty.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,4 @@ def self.delete(*args)
require 'httparty/exceptions'
require 'httparty/request'
require 'httparty/response'
require 'httparty/json'
require 'httparty/xml'
require 'httparty/parsers'
64 changes: 0 additions & 64 deletions lib/httparty/json.rb

This file was deleted.

4 changes: 4 additions & 0 deletions lib/httparty/parsers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Dir[File.dirname(__FILE__) + "/parsers/*.rb"].sort.each do |path|
filename = File.basename(path)
require "httparty/parsers/#{filename}"
end
66 changes: 66 additions & 0 deletions lib/httparty/parsers/json.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Copyright (c) 2004-2008 David Heinemeier Hansson
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

require 'yaml'
require 'strscan'

module HTTParty
module Parsers
module JSON #:nodoc:
class ParseError < StandardError; end

def self.decode(json)
YAML.load(convert_json_to_yaml(json))
rescue ArgumentError => e
raise ParseError, "Invalid JSON string"
end

protected
# matches YAML-formatted dates
DATE_REGEX = /^\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?$/

# Ensure that ":" and "," are always followed by a space
def self.convert_json_to_yaml(json) #:nodoc:
scanner, quoting, marks, pos, times = StringScanner.new(json), false, [], nil, []
while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/)
case char = scanner[1]
when '"', "'"
if !quoting
quoting = char
pos = scanner.pos
elsif quoting == char
if json[pos..scanner.pos-2] =~ DATE_REGEX
# found a date, track the exact positions of the quotes so we can remove them later.
# oh, and increment them for each current mark, each one is an extra padded space that bumps
# the position in the final YAML output
total_marks = marks.size
times << pos+total_marks << scanner.pos+total_marks
end
quoting = false
end
when ":",","
marks << scanner.pos - 1 unless quoting
end
end

if marks.empty?
json.gsub(/\\\//, '/')
else
left_pos = [-1].push(*marks)
right_pos = marks << json.length
output = []
left_pos.each_with_index do |left, i|
output << json[left.succ..right_pos[i]]
end
output = output * " "

times.each { |i| output[i-1] = ' ' }
output.gsub!(/\\\//, '/')
output
end
end
end
end
end
44 changes: 23 additions & 21 deletions lib/httparty/xml.rb → lib/httparty/parsers/xml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -178,30 +178,32 @@ def to_s
end

module HTTParty
module XML
def self.parse(xml)
stack = []
parser = REXML::Parsers::BaseParser.new(xml)

while true
event = parser.pull
case event[0]
when :end_document
break
when :end_doctype, :start_doctype
# do nothing
when :start_element
stack.push REXMLUtilityNode.new(event[1], event[2])
when :end_element
if stack.size > 1
temp = stack.pop
stack.last.add_node(temp)
module Parsers
module XML
def self.parse(xml)
stack = []
parser = REXML::Parsers::BaseParser.new(xml)

while true
event = parser.pull
case event[0]
when :end_document
break
when :end_doctype, :start_doctype
# do nothing
when :start_element
stack.push REXMLUtilityNode.new(event[1], event[2])
when :end_element
if stack.size > 1
temp = stack.pop
stack.last.add_node(temp)
end
when :text, :cdata
stack.last.add_node(event[1]) unless event[1].strip.length == 0 || stack.empty?
end
when :text, :cdata
stack.last.add_node(event[1]) unless event[1].strip.length == 0 || stack.empty?
end
stack.pop.to_hash
end
stack.pop.to_hash
end
end
end
4 changes: 2 additions & 2 deletions lib/httparty/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ def parse_response(body)
return nil if body.nil? or body.empty?
case format
when :xml
HTTParty::XML.parse(body)
HTTParty::Parsers::XML.parse(body)
when :json
HTTParty::JSON.decode(body)
HTTParty::Parsers::JSON.decode(body)
else
body
end
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require File.join(File.dirname(__FILE__), '..', 'spec_helper')
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper')

describe HTTParty::JSON do
describe HTTParty::Parsers::JSON do
TESTS = {
%q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}},
%q({returnTo:{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}},
Expand Down Expand Up @@ -28,14 +28,14 @@
TESTS.each do |json, expected|
it "should decode json (#{json})" do
lambda {
HTTParty::JSON.decode(json).should == expected
HTTParty::Parsers::JSON.decode(json).should == expected
}.should_not raise_error
end
end

it "should raise error for failed decoding" do
lambda {
HTTParty::JSON.decode(%({: 1}))
}.should raise_error(HTTParty::JSON::ParseError)
HTTParty::Parsers::JSON.decode(%({: 1}))
}.should raise_error(HTTParty::Parsers::JSON::ParseError)
end
end
Loading

0 comments on commit 9aa7c84

Please sign in to comment.