Skip to content

Instantly share code, notes, and snippets.

@chenyukang
Last active December 10, 2015 04:18
Show Gist options
  • Save chenyukang/4380597 to your computer and use it in GitHub Desktop.
Save chenyukang/4380597 to your computer and use it in GitHub Desktop.
# Class Tree
# ruby prog.rb > class.dot;dot -Tpng class.dot -o class.png;
def readable(str)
if str.length >= 30
return false
end
for k in 0..str.length-1
s = str[k]
if not ((s>='a' and s<='z') or (s>='A' and s<='Z') or (s >='0' and s<='9'))
return false
end
end
return true
end
class ClassTreeNode
attr_accessor :klass, :subclasses, :objects
def initialize(klass)
@klass = klass
@subclasses = {}
@objects = []
end
def add_class(klass)
@subclasses[klass] ||= ClassTreeNode.new(klass)
end
def add_object(object)
@objects << object
self
end
def draw(draw_obj = false)
res = ""
res += "digraph G {\n ratio=auto;\n"
res += draw_it(draw_obj)
res += "\n}\n"
return res
end
def draw_it(draw_obj = false)
res = ""
@subclasses.each do |k, v|
res += "\"#{k}\" -> \"#{@klass}\";\n"
end
if draw_obj
@objects.each do |k|
if @klass != "".class and k.to_s != "" and readable(k.to_s)
res += "\"#{k}\" -> \"#{@klass}\" [color=\"blue\"];\n"
end
end
end
@subclasses.each do |k, v|
res += v.draw_it(draw_obj)
end
return res
end
public :draw, :draw_it
end
# Creates or updates a klass_tree.
# When updating no classes or objects are removed
def object_browser(classtree = ClassTreeNode.new(Kernel))
ObjectSpace.each_object do | x |
classnode = classtree
x.class.ancestors.reverse[1..-1] \
.inject(classtree){ | classnode, klass |
classnode.add_class(klass)
}.add_object(x)
end
classtree
end
class Demo
end
demo = Demo.new()
class SubDemo < Demo
end
sub = SubDemo.new()
obj = object_browser()
puts obj.draw(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment