summaryrefslogtreecommitdiff
path: root/lib/scale/node.rb
blob: c71d589c284e7ea64509c37df3450f186a2a4155 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
42
43
44
45
46
47
48
49
require 'virtus'

module Scale
  module Node
    include Enumerable
    include Virtus.module
    attr_reader :content

    def children
      @children ||= []
    end

    def add(node)
      children.push(node)
    end

    def each
      children.each do |child|
        yield child
      end
    end

    def to_xml
      builder = Nokogiri::XML::Builder.new do |xml|
        append_to(xml)
      end
      builder.to_xml
    end

    def append_to(builder)
      builder.send(xml_tag.to_sym, *xml_parameters) do
        each do |node|
          node.append_to(builder)
        end
      end
    end

    def xml_attributes
      attributes.delete_if { |key, value| value.nil? }
    end

    private

    def xml_parameters
      return [xml_attributes] if content.nil?
      [content, xml_attributes]
    end
  end
end