Skip to content
Browse files

Implemented basic support for type casting.

  • Loading branch information...
1 parent 675bbf8 commit b530046963d926881c7590caeac9a76349544190 @tylerhunt committed
Showing with 35 additions and 1 deletion.
  1. +12 −1 lib/relief/element.rb
  2. +23 −0 spec/parser_spec.rb
View
13 lib/relief/element.rb
@@ -13,12 +13,23 @@ def initialize(name, options, &block)
def parse(document)
@children.inject({}) do |values, element|
key = element.options[:as] || element.name
+ type = element.options[:type]
values[key] = begin
target = (document / element.xpath)
parse_node = lambda { |target|
- element.children.any? ? element.parse(target) : target.to_s
+ if element.children.any?
+ element.parse(target)
+ else
+ value = target.to_s
+
+ if type == Integer then value.to_i
+ elsif type == Float then value.to_f
+ elsif type == Date then Date.parse(value)
+ else value
+ end
+ end
}
if element.options[:collection]
View
23 spec/parser_spec.rb
@@ -123,4 +123,27 @@
photos.should == { :name => ['Cucumbers', 'Lemons'] }
end
+
+ it "parses elements with type casting" do
+ parser = Relief::Parser.new(:photo) do
+ element :id, :type => Integer
+ element :rating, :type => Float
+ element :published, :type => Date
+ 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>
+ </photo>
+ XML
+
+ photo.should == {
+ :id => 86634,
+ :rating => 3.5,
+ :published => Date.parse('2009-05-08T18:23:26-07:00')
+ }
+ end
end

0 comments on commit b530046

Please sign in to comment.
Something went wrong with that request. Please try again.