From 5abc390c91cd117d540e8bfd19d667ca39cf5066 Mon Sep 17 00:00:00 2001 From: geemus Date: Fri, 18 Jun 2010 14:35:29 -0700 Subject: [PATCH] add initial ToHashParser --- lib/fog/parser.rb | 59 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/lib/fog/parser.rb b/lib/fog/parser.rb index f7cb15474..8031c009e 100644 --- a/lib/fog/parser.rb +++ b/lib/fog/parser.rb @@ -24,3 +24,62 @@ module Fog 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