Creating an XML doc from a configuration file using lineparser

Lineparser is a gem I recently wrote to parse configuration files that I'm planning to use with Rails, and while doing so, I discovered I needed an XML representation of the configuration file.

The idea is that it's easier to select nodes from XPath than it is to tinker with individual array elements.

Here's an example:

require 'lineparser'

lines =<<LINES
app_path: /tmp
app: blog
resources: posts

welcome
  model
    foo
  controller + views
    index   v
      v: ... link_to "My Blog", controller: "posts" 
LINES

  patterns = [
    [:root, 'app_path: :app_path', :app_path],
    [:root, 'app: :app', :app],
    [:root, 'resources: :resources', :resources],
    [:root, ':resource', :resource],
      [:resource, 'model', :model],
        [:model, ':class_name', :model_class],
      [:resource, /controller \+ views/, :resource_cv],
        [:resource_cv, /\w+\s+[av]{1,2}/, :resource_cv_av],
    [:all, /#/]
  ]

lp = LineParser.new patterns
lp.parse lines
puts Rexle.new(lp.to_xml).xml pretty: true

output:

<?xml version='1.0' encoding='UTF-8'?>
<root>
  <app_path app_path='/tmp'>app_path: /tmp</app_path>
  <app app='blog'>app: blog</app>
  <resources resources='posts'>resources: posts</resources>
  <resource resource='welcome'>
welcome
model
  foo
controller + views
  index   v
      v: ... link_to "My Blog", controller: "posts" 
<model>
  model
foo
  <model_class class_name='foo'>foo</model_class>
</model>
<resource_cv>
  controller + views
index v
  v: ... link_to "My Blog", controller: "posts" 
  <resource_cv_av>index   v
v: ... link_to "My Blog", controller: "posts" </resource_cv_av>
</resource_cv>
</resource> </root>

The XML document however messy looking it appears does the job of representing the order and hierarchy of items as they appear in the configuration file. It also includes the matched keywords as node attributes, while storing the original lines below it within the node as text.

Resources

Tags:
Source:
1521hrs.txt
Published:
12-03-2014 15:21