2014-08-15 21:29:48 +02:00
|
|
|
# We transform objects into a tree of nodes
|
|
|
|
|
|
|
|
module Sof
|
2014-08-16 11:34:25 +02:00
|
|
|
#abstract base class for nodes in the tree
|
2014-08-15 21:29:48 +02:00
|
|
|
class Node
|
2014-08-16 11:34:25 +02:00
|
|
|
# must be able to output to a stream
|
|
|
|
def out io ,level
|
|
|
|
raise "abstract #{self}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class SimpleNode < Node
|
2014-08-16 14:16:07 +02:00
|
|
|
def initialize data
|
|
|
|
@data = data
|
2014-08-15 21:29:48 +02:00
|
|
|
end
|
2014-08-16 14:16:07 +02:00
|
|
|
attr_accessor :data
|
2014-08-16 10:43:41 +02:00
|
|
|
def out io , level
|
2014-08-16 14:16:07 +02:00
|
|
|
io.write(data) if data
|
2014-08-16 10:43:41 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2014-08-16 14:16:07 +02:00
|
|
|
class NodeList < SimpleNode
|
2014-08-16 11:34:25 +02:00
|
|
|
def initialize
|
2014-08-16 14:16:07 +02:00
|
|
|
super(nil)
|
2014-08-16 10:43:41 +02:00
|
|
|
@children = []
|
|
|
|
end
|
|
|
|
attr_accessor :children
|
|
|
|
|
2014-08-15 21:29:48 +02:00
|
|
|
def add child
|
2014-08-16 11:34:25 +02:00
|
|
|
child = SimpleNode.new(child) if(child.is_a? String)
|
2014-08-15 21:29:48 +02:00
|
|
|
@children << child
|
|
|
|
end
|
|
|
|
|
|
|
|
def out io , level = 0
|
2014-08-16 14:16:07 +02:00
|
|
|
super
|
2014-08-16 10:43:41 +02:00
|
|
|
return if @children.empty?
|
|
|
|
first = @children.first
|
|
|
|
io.write "-"
|
2014-08-15 21:29:48 +02:00
|
|
|
first.out(io , level + 1)
|
|
|
|
indent = " " * level
|
2014-08-16 10:43:41 +02:00
|
|
|
@children.each_with_index do |child , i|
|
|
|
|
next if i == 0 # done already
|
|
|
|
io.write "\n"
|
2014-08-15 21:29:48 +02:00
|
|
|
io.write indent
|
|
|
|
io.write "-"
|
|
|
|
child.out(io , level + 1)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|