Class Ambling::Utils::SettingsGenerator
In: lib/ambling/utils.rb
Parent: Object

generate a ruby class from the amchart settings XML

Methods

generate  

Public Instance methods

Turn the provided xml into a class for chart_type

[Source]

# File lib/ambling/utils.rb, line 57
      def generate(chart_type, xml)
        require 'xmlparser'
        @parser=XML::Parser.new
        class <<@parser
          # enable additional events
          attr_accessor :comment, :xmlDecl
        end
        
        current_section_data = section_data = SettingsSection.new("xml")
        section_data_stack = []
        current_element = nil
        last_element = nil
        # Sam Ruby has code that does something very much like this
        @parser.parse(xml) do |type, name, data|
          case type
          when XML::Parser::START_ELEM
            # name = element name  ; data = hash of attributes
            if not current_section_data.values[name]
              current_section_data.values[name] = SettingsSection.new(name, data ? data.keys : [])
            end
            section_data_stack << current_section_data
            current_section_data = current_section_data.values[name]
            current_element = name
            last_element = nil
          when XML::Parser::END_ELEM
            # name = element name  ; data = nil
            end_section_data = current_section_data
            current_section_data = section_data_stack.pop
            last_element = current_element
            current_element = nil
          when XML::Parser::COMMENT                           
            # name = nil           ; data = string
            if current_section_data.values.empty?
              current_section_data.comment = data
            else
              current_section_data.values[last_element].comment = data
            end
          end
        end
        
        top_level = section_data.values.first.last
        top_level.comment = section_data.comment if top_level.comment.blank?
        
        cdef = "# Auto generated from XML file\n"
        cef << "require 'ambling/base'\nmodule Ambling\n  class #{chart_type.to_s.camelize}\n"
        cdef << top_level.to_class_s(4)
        cdef << "\n  end\nend\n"
      end

[Validate]