Module: ConfigMan::Parsers::XML

Defined in:
lib/configman/parsers/xml.rb

Constant Summary collapse

CONFIG_FILE_PATH =
File.join(Dir.pwd, '.config').freeze

Class Method Summary collapse

Class Method Details

.parse(file_path) ⇒ Object

Parse the .config file and return a hash of the configuration values Parse the .config file and return a hash of the configuration values

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/configman/parsers/xml.rb', line 14

def self.parse(file_path)
  raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)

  xml_file = File.new(file_path)
  document = REXML::Document.new(xml_file)
  parsed_config = {}

  # Recursive lambda to parse nested elements
  parse_element = lambda do |element|
    if element.has_elements?
      element_hash = {}
      element.each_element do |child|
        element_hash[child.name] = parse_element.call(child)
      end
      element_hash
    else
      element.text
    end
  end

  document.elements.each('config/*') do |element|
    parsed_config[element.name] = parse_element.call(element)
  end

  raise ArgumentError, "Invalid XML format in #{file_path}" unless parsed_config.is_a?(Hash)

  parsed_config
end

.update(key, new_value) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/configman/parsers/xml.rb', line 43

def self.update(key, new_value)
  existing_config = parse(CONFIG_FILE_PATH)
  existing_config[key] = new_value

  doc = REXML::Document.new
  doc.add_element('config')
  existing_config.each { |k, v| doc.root.add_element(k).text = v }

  formatter = REXML::Formatters::Pretty.new
  File.open(CONFIG_FILE_PATH, 'w') do |file|
    formatter.write(doc, file)
  end
end

.write(config_hash) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/configman/parsers/xml.rb', line 57

def self.write(config_hash)
  # Access the loaded modules and expected keys from the main class
  loaded_modules = ConfigMan.used_modules
  expected_keys = ConfigMan.expected_keys

  # Sort the keys into their respective sections
  sorted_config = Utils.sort_into_sections(config_hash, expected_keys, loaded_modules)

  doc = REXML::Document.new
  doc.add_element('config')

  sorted_config.each do |section, section_data|
    section_element = doc.root.add_element(section)
    section_data.each { |k, v| section_element.add_element(k).text = v }
  end

  formatter = REXML::Formatters::Pretty.new
  File.open(CONFIG_FILE_PATH, 'w') do |file|
    formatter.write(doc, file)
  end
end