rubyx/lib/sof/node.rb

45 lines
880 B
Ruby
Raw Normal View History

# We transform objects into a tree of nodes
module Sof
2014-08-16 12:34:25 +03:00
#abstract base class for nodes in the tree
class Node
2014-08-18 13:01:52 +03:00
include Util
2014-08-16 12:34:25 +03:00
# must be able to output to a stream
def out io ,level
raise "abstract #{self}"
end
end
class SimpleNode < Node
2014-08-16 15:16:07 +03:00
def initialize data
@data = data
end
2014-08-18 13:01:52 +03:00
attr_reader :data
def out io , level
io.write(data)
end
end
class ObjectNode < Node
def initialize data
@data = data
@children = []
end
2014-08-18 13:01:52 +03:00
attr_reader :children , :data
def add k , v
@children << [k,v]
end
def out io , level = 0
io.write(@data)
2014-08-18 12:49:38 +03:00
indent = " " * (level + 1)
@children.each_with_index do |child , i|
k , v = child
2014-08-18 12:49:38 +03:00
io.write "\n#{indent}"
k.out(io , level + 2)
io.write " "
v.out(io , level + 2)
end
end
end
end