File: node.rb

package info (click to toggle)
ruby-kdl 1.0.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 480 kB
  • sloc: ruby: 6,667; yacc: 72; sh: 5; makefile: 4
file content (62 lines) | stat: -rw-r--r-- 1,527 bytes parent folder | download | duplicates (2)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
module KDL
  class Node
    attr_accessor :name, :arguments, :properties, :children, :type

    def initialize(name, arguments = [], properties = {}, children = [], type: nil)
      @name = name
      @arguments = arguments
      @properties = properties
      @children = children
      @type = type
    end

    def to_s(level = 0)
      indent = '    ' * level
      s = "#{indent}#{type ? "(#{id_to_s type})" : ''}#{id_to_s name}"
      unless arguments.empty?
        s += " #{arguments.map(&:to_s).join(' ')}"
      end
      unless properties.empty?
        s += " #{properties.map { |k, v| "#{id_to_s k}=#{v}" }.join(' ')}"
      end
      unless children.empty?
        s += " {\n"
        s += children.map { |c| "#{c.to_s(level + 1)}\n" }.join("\n")
        s += "#{indent}}"
      end
      s
    end

    def ==(other)
      return false unless other.is_a?(Node)

      name       == other.name       &&
      arguments  == other.arguments  &&
      properties == other.properties &&
      children   == other.children
    end

    def as_type(type, parser = nil)
      if parser.nil?
        @type = type
        self
      else
        result = parser.call(self, type)

        return self.as_type(type) if result.nil?

        unless result.is_a?(::KDL::Node)
          raise ArgumentError, "expected parser to return an instance of ::KDL::Node, got `#{result.class}'"
        end

        result
      end
    end

    private

    def id_to_s(id)
      StringDumper.stringify_identifier(id)
    end
  end
end