Permalink
Browse files

Fixed type casting for empty element values.

Added support for DateTime values.
  • Loading branch information...
1 parent 78d63ba commit 5eda76edc61d0b6056ab216c68ef44069540688b @tylerhunt committed May 13, 2009
Showing with 39 additions and 4 deletions.
  1. +4 −1 lib/relief/element.rb
  2. +35 −3 spec/parser_spec.rb
View
@@ -24,9 +24,12 @@ def parse(document)
else
value = target.to_s
- if type == Integer then value.to_i
+ if type.nil? then value
+ elsif value.empty? then nil
+ elsif type == Integer then value.to_i
elsif type == Float then value.to_f
elsif type == Date then Date.parse(value)
+ elsif type == DateTime then DateTime.parse(value)
elsif type.is_a?(Parser) then type.parse(document)
else value
end
View
@@ -128,22 +128,25 @@
parser = Relief::Parser.new(:photo) do
element :id, :type => Integer
element :rating, :type => Float
- element :published, :type => Date
+ element :taken, :type => Date
+ element :published, :type => DateTime
end
photo = parser.parse(<<-XML)
<?xml version="1.0" encoding="UTF-8"?>
<photo>
<id>86634</id>
<rating>3.5</rating>
- <published>2009-05-08T18:23:26-07:00</url>
+ <taken>2009-05-06</taken>
+ <published>2009-05-08T18:23:26-07:00</published>
</photo>
XML
photo.should == {
:id => 86634,
:rating => 3.5,
- :published => Date.parse('2009-05-08T18:23:26-07:00')
+ :taken => Date.new(2009, 5, 6),
+ :published => DateTime.new(2009, 5, 8, 18, 23, 26, Date.time_to_day_fraction(-7, 0, 0))
}
end
@@ -174,4 +177,33 @@
}
}
end
+
+ it "doesn't type cast elements with empty values" do
+ parser = Relief::Parser.new(:photo) do
+ element :name
+ element :id, :type => Integer
+ element :rating, :type => Float
+ element :taken, :type => Date
+ element :published, :type => DateTime
+ end
+
+ photo = parser.parse(<<-XML)
+ <?xml version="1.0" encoding="UTF-8"?>
+ <photo>
+ <name></name>
+ <id></id>
+ <rating></rating>
+ <taken></taken>
+ <published></published>
+ </photo>
+ XML
+
+ photo.should == {
+ :name => '',
+ :id => nil,
+ :rating => nil,
+ :taken => nil,
+ :published => nil
+ }
+ end
end

0 comments on commit 5eda76e

Please sign in to comment.