Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Retain extra attributes on elements tagged with "type='array'".

  • Loading branch information...
commit a2593bd440c9d18fd60d597e0845ed6ae1b25c94 1 parent 5057130
@mdub mdub authored pengwynn committed
Showing with 27 additions and 2 deletions.
  1. +14 −2 lib/crack/xml.rb
  2. +13 −0 test/xml_test.rb
View
16 lib/crack/xml.rb
@@ -82,7 +82,7 @@ class << f
if @text
t = typecast_value( unnormalize_xml_entities( inner_html ) )
- t.class.send(:attr_accessor, :attributes)
+ t.class.send(:include, Crack::HasAttributes)
t.attributes = attributes
return { name => t }
else
@@ -91,7 +91,7 @@ class << f
out = nil
if @type == "array"
- out = []
+ out = Crack::Array.new
groups.each do |k, v|
if v.size == 1
out << v.first.to_hash.entries.first.last
@@ -99,6 +99,8 @@ class << f
out << v.map{|e| e.to_hash[k]}
end
end
+ out.attributes = attributes.reject { |k,v| k == "type" }
+
out = out.flatten
else # If Hash
@@ -185,6 +187,7 @@ def unnormalize_xml_entities value
end
module Crack
+
class XML
def self.parse(xml)
stack = []
@@ -211,4 +214,13 @@ def self.parse(xml)
stack.length > 0 ? stack.pop.to_hash : {}
end
end
+
+ module HasAttributes
+ attr_accessor :attributes
+ end
+
+ class Array < ::Array
+ include HasAttributes
+ end
+
end
View
13 test/xml_test.rb
@@ -399,6 +399,19 @@ class XmlTest < Test::Unit::TestCase
Crack::XML.parse(blog_xml).should == expected_blog_hash
end
+ should "should provide access to additional attributes on an array element" do
+ blog_xml = <<-XML
+ <blog>
+ <posts type="array" total="456">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ XML
+ hash = Crack::XML.parse(blog_xml)
+ hash["blog"]["posts"].attributes.should == {"total" => "456"}
+ end
+
should "should handle file types (ActiveSupport Compatible)" do
blog_xml = <<-XML
<blog>
Please sign in to comment.
Something went wrong with that request. Please try again.