Skip to content

Instantly share code, notes, and snippets.

@tonymarklove
Created September 16, 2020 14:13
Show Gist options
  • Select an option

  • Save tonymarklove/30c89f455dafdf2ba8b79a7c2a46b84c to your computer and use it in GitHub Desktop.

Select an option

Save tonymarklove/30c89f455dafdf2ba8b79a7c2a46b84c to your computer and use it in GitHub Desktop.
Print the Rails controller inheritance tree
#!/usr/bin/env ruby
require File.expand_path('../../config/environment', __FILE__)
Rails.application.eager_load!
def build_tree(branch, ancestors)
return if ancestors.empty?
first, *tail = *ancestors
branch[first] ||= {}
build_tree(branch[first], tail)
end
def print_tree_indented(branch, depth=0)
return if branch.empty?
indent = ' ' * depth
branch.sort_by { |(k,v)| k.name }.each_with_index do |(name, sub_branch), index|
puts "#{indent}#{name}"
print_tree_indented(sub_branch, depth+1)
end
end
def print_tree(branch, indent = '', top_level: true)
return if branch.empty?
branch.sort_by { |(k,v)| k.name }.each_with_index do |(name, sub_branch), index|
last_item = (index == branch.size-1)
stopper = (last_item ? ' └ ' : ' ├ ') unless top_level
puts "#{indent}#{stopper}#{name}"
new_indent = (last_item ? ' ' : ' │ ') unless top_level
print_tree(sub_branch, "#{indent}#{new_indent}", top_level: false)
end
end
def skip_controller?(controller)
# Customise which controllers get added to the tree.
false
end
all_controllers = ObjectSpace.each_object(Class).select do |klass|
klass.respond_to?(:name) && klass.name&.end_with?('Controller')
end
tree = all_controllers.each_with_object({}) do |controller, memo|
ancestors = (controller.ancestors & all_controllers).reverse
ancestors.unshift(ancestors.first.superclass)
next if skip_controller?(controller)
build_tree(memo, ancestors)
end
print_tree(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment