Class: Ambling::Utils::SettingsGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/ambling/utils.rb

Overview

generate a ruby class from the amchart settings XML

Instance Method Summary collapse

Instance Method Details

#generate(chart_type, xml) ⇒ Object

Turn the provided xml into a class for chart_type



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/ambling/utils.rb', line 60

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
        if current_section_data.values[last_element]
          current_section_data.values[last_element].comment = data
        end
      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"
  cdef << "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