Browse files

Implemented custom type casting with Parser.

  • Loading branch information...
1 parent b530046 commit 00c2947bbbce3e55249b5fa666b2da950fb54996 @tylerhunt committed May 9, 2009
Showing with 32 additions and 3 deletions.
  1. +2 −1 lib/relief/element.rb
  2. +2 −2 lib/relief/parser.rb
  3. +28 −0 spec/parser_spec.rb
View
3 lib/relief/element.rb
@@ -2,7 +2,7 @@ module Relief
class Element
attr_reader :name, :options, :children
- def initialize(name, options, &block)
+ def initialize(name=nil, options={}, &block)
@name = name
@options = options
@children = []
@@ -27,6 +27,7 @@ def parse(document)
if type == Integer then value.to_i
elsif type == Float then value.to_f
elsif type == Date then Date.parse(value)
+ elsif type.is_a?(Parser) then type.parse(document)
else value
end
end
View
4 lib/relief/parser.rb
@@ -5,13 +5,13 @@ module Relief
class Parser
attr_reader :root
- def initialize(name, options={}, &block)
+ def initialize(name=nil, options={}, &block)
@root = Element.new(name, options, &block)
end
def parse(document)
unless document.is_a?(Nokogiri::XML::NodeSet)
- document = Nokogiri::XML(document)
+ document = Nokogiri::XML(document.to_s)
end
@root.parse(document)
View
28 spec/parser_spec.rb
@@ -146,4 +146,32 @@
:published => Date.parse('2009-05-08T18:23:26-07:00')
}
end
+
+ it "parses elements with custom type casting" do
+ author = Relief::Parser.new do
+ element :name
+ element :email
+ end
+
+ parser = Relief::Parser.new(:photo) do
+ element :author, :type => author
+ end
+
+ photo = parser.parse(<<-XML)
+ <?xml version="1.0" encoding="UTF-8"?>
+ <photo>
+ <author>
+ <name>Jennifer Stone</name>
+ <email>jstone@example.com</email>
+ </author>
+ </photo>
+ XML
+
+ photo.should == {
+ :author => {
+ :name => 'Jennifer Stone',
+ :email => 'jstone@example.com'
+ }
+ }
+ end
end

0 comments on commit 00c2947

Please sign in to comment.