Skip to content

Commit

Permalink
add initial ToHashParser
Browse files Browse the repository at this point in the history
  • Loading branch information
geemus committed Jun 18, 2010
1 parent 0150e77 commit 5abc390
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions lib/fog/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,62 @@ def start_element(name, attrs = [])
end
end
end

module Fog
class ToHashParser

def initialize
@stack = []
end

def characters(string)
@value ||= ''
@value << string.strip
end

def end_element(name)
@stack.pop
unless @value.empty?
@stack.last[name.to_sym] = @value
@value = ''
end
end

def body
@stack.first
end

def start_element(name, attributes = [])
@value = ''
parsed_attributes = {}
until attributes.empty?
if attributes.first.is_a?(Array)
key, value = attributes.shift
else
key, value = attributes.shift, attributes.shift
end
parsed_attributes[key.to_sym] = value
end
if @stack.last.is_a?(Array)
@stack.last << {name.to_sym => parsed_attributes}
else
data = if @stack.empty?
@stack.push(parsed_attributes)
parsed_attributes
elsif @stack.last[name.to_sym]
unless @stack.last[name.to_sym].is_a?(Array)
@stack.last[name.to_sym] = [@stack.last[name.to_sym]]
end
@stack.last[name.to_sym] << parsed_attributes
@stack.last[name.to_sym].last
else
@stack.last[name.to_sym] = {}
@stack.last[name.to_sym].merge!(parsed_attributes)
@stack.last[name.to_sym]
end
@stack.push(data)
end
end

end
end

0 comments on commit 5abc390

Please sign in to comment.