Skip to content

Instantly share code, notes, and snippets.

@jhecking
Last active December 28, 2015 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhecking/7578183 to your computer and use it in GitHub Desktop.
Save jhecking/7578183 to your computer and use it in GitHub Desktop.
Slightly adapted version of Nick Sieger's script to dump Ruby's exception hierarchy. If run with `bundle exec` or `rails console` the hierarchy will include all exception classes defined in any of the included gems as well. Therefore I found it necessary to determine the common ancestors of the Exception class at run-time rather than hard code t…
def class_hierarchy(root, exclude = [])
common_ancestors = root.ancestors.drop(1)
descendants = []
tree = {}
ObjectSpace.each_object(Class) do |cls|
next unless cls.ancestors.include? root
next if descendants.include? cls
case exclude
when Class, Array
next unless (Array(exclude) & cls.ancestors).empty?
when Regexp, String
next if Regexp.compile(exclude).match(cls.to_s)
end
descendants << cls
ancestors = cls.ancestors - common_ancestors
ancestors.reverse.inject(tree) {|memo,klass| memo[klass] ||= {}}
end
tree
end
def print_tree(t, indent = 0)
t.keys.sort_by(&:name).each do |k|
puts " " * indent + k.to_s
print_tree(t[k], indent + 1)
end
end
print_tree(class_hierarchy(Exception, /^Errno::/))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment