Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/cocainum/overrides.rb

Instance Method Summary collapse

Instance Method Details

#to_xml(recurse = false, default_root = 'root') ⇒ Object



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
# File 'lib/cocainum/overrides.rb', line 66

def to_xml(recurse = false, default_root = 'root')
  attributes = []
  children = []
  each do |k, v|
    if Hash === v
      a, c = v.to_xml(true)
      if c.size > 0
        children << '<%s%s>%s</%s>' % [k, a.size > 0 ? ' ' + a.join(' ') : '', c.join, k]
      else
        children << '<%s%s />' % [k, a.size > 0 ? ' ' + a.join(' ') : '']
      end
    elsif Array === v
      key = v.shift
      if key[0] == '#'
        children << '%s' % [v.to_xml(key.gsub('#',''))]
      else
        children << '<%s>%s</%s>' % [k, v.to_xml(key), k]
      end
    else
      attributes << '%s="%s"' % [k, v]
    end
  end
  if recurse
    [attributes, children]
  else
    if children.size > 1 || attributes.size > 0
      if children.size > 0
        '<%s%s>%s</%s>' % [default_root, attributes.size > 0 ? ' ' + attributes.join(' ') : '', children.join, default_root]
      else
        '<%s %s />' % [default_root, attributes.join(' ')]
      end
    else
      children[0]
    end
  end
end