Module: XML

Defined in:
lib/xml-dsl/compile.rb

Class Method Summary collapse

Class Method Details

.analyze_elem(elem) ⇒ Object



37
38
39
# File 'lib/xml-dsl/compile.rb', line 37

def self.analyze_elem elem
  [elem[0], get_elem_part(elem, Hash), get_elem_part(elem, [Array, String])]
end

.brackets(tag) ⇒ Object



33
34
35
# File 'lib/xml-dsl/compile.rb', line 33

def self.brackets tag
  '<' + tag + '>'
end

.compile_attrs(attrs) ⇒ Object



27
28
29
30
31
# File 'lib/xml-dsl/compile.rb', line 27

def self.compile_attrs attrs
  attrs.map do |name, value|
    "#{name}=#{value.to_s.encode(xml: :attr)}"
  end.join ' '
end

.compile_elems(elems) ⇒ Object



14
15
16
17
18
# File 'lib/xml-dsl/compile.rb', line 14

def self.compile_elems elems
  elems.map do |elem|
    tagged(*analyze_elem(elem))
  end.join
end

.from_array(array, format: true) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/xml-dsl/compile.rb', line 6

def self.from_array array, format: true
  xml = compile_elems(array)

  return xml if not format

  Nokogiri::XML(xml, &:noblanks).to_xml(indent: 4, &:no_declaration)
end

.get_elem_part(elem, classes) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/xml-dsl/compile.rb', line 41

def self.get_elem_part elem, classes
  raise "Error: An array longer than 3 representing an element is detected.: \
         #{elem}" if elem.length > 3

  classes = [classes] if classes.is_a? Class
  in_classes = lambda { |x| classes.map{ |klass| x.is_a? klass }.any? }

  if in_classes.call elem[1]
    elem[1]
  elsif in_classes.call elem[2]
    elem[2]
  else
    classes[0].new
  end
end

.tagged(tag, attrs, body) ⇒ Object



20
21
22
23
24
25
# File 'lib/xml-dsl/compile.rb', line 20

def self.tagged tag, attrs, body
  tag = tag.to_s
  brackets(tag + (attrs.length > 0 ? ' ' + compile_attrs(attrs) : '')) \
      + (body.is_a?(String) ? body : compile_elems(body)) \
      + brackets('/' + tag)
end