Permalink
Browse files

Changed so that the .decode method always return an Array.

  • Loading branch information...
1 parent d28b242 commit 8978b53a1677b3a0d5a61ec65c7ea6d9ac942074 Anders Törnqvist committed Jun 15, 2011
View
@@ -31,20 +31,21 @@ def accept; 'application/json, */*'; end
# @return [String] "application/json"
def content_type; 'application/json'; end
- # Converts a JSON formatted String to a Hash.
+ # Converts a JSON formatted String to an Array of a Hashes.
#
# === Example:
# Json.decode("{\"root\":{\"body\":\"I am a body\"}}")
- # # => { root: { body: 'I am a body' } }
+ # # => [{ 'root': { 'body': 'I am a body' } }]
#
# @param json [String]
# @param options is not used.
#
- # @return [Hash]
+ # @return [Array<Hash>]
def decode(json, options=nil)
raise ArgumentError unless json.is_a?(String)
- Yajl::Parser.parse(json)
+ result = Yajl::Parser.parse(json)
+ result.is_a?(Array) ? result : [result].compact
end
# Converts a Hash to a JSON formatted String.
View
@@ -21,15 +21,18 @@ def encode(hash, options = nil)
def decode(xml, options)
xpath = options.fetch(:xpath)
+ # Converts an XML formatted String to an Array of Hashes.
doc = Nokogiri::XML(xml)
nodes = doc.xpath(xpath)
case nodes.size
when 0
{}
+ [{}]
when 1
elements_to_hash(nodes.first.children)
+ [elements_to_hash(nodes.first.children)]
else
nodes.map { |node| elements_to_hash(node.children) }
end
@@ -63,17 +63,17 @@ def valid?
def to_object
return self unless @translator
- @translator.call(@klass, read_body).tap do |instance|
+ body = read_body ? read_body.first : nil
+
+ @translator.call(@klass, body).tap do |instance|
instance.response = self
end
end
def to_collection
return self unless @translator
- body = read_body.is_a?(Hash) ? [read_body] : read_body
-
- (body || []).map do |hash|
+ (read_body || []).map do |hash|
@translator.call(@klass, hash).tap do |instance|
instance.response = self
end
@@ -12,7 +12,7 @@
describe '.decode(json)' do
json = Yajl::Encoder.encode( { :foo => 12425125, :bar => "some string" })
- expected = { 'foo' => 12425125, 'bar' => "some string" }
+ expected = [{ 'foo' => 12425125, 'bar' => "some string" }]
it { subject.decode(json).should == expected }
end
@@ -87,11 +87,11 @@
describe '.decode(xml, xpath)' do
context 'when one item' do
- it { subject.decode(xml, :xpath => '//zone').should == attributes }
+ it { subject.decode(xml, :xpath => '//zone').should == [attributes] }
end
context 'when 0 items' do
- it { subject.decode(xml, :xpath => '//xx0').should == {} }
+ it { subject.decode(xml, :xpath => '//xx0').should == [{}] }
end
context 'when a collection of two items' do

0 comments on commit 8978b53

Please sign in to comment.