Skip to content

Instantly share code, notes, and snippets.

@gmcculloug
Created August 3, 2018 12:36
Show Gist options
  • Save gmcculloug/b95f24cb460a9fb6f1d6555004e1e332 to your computer and use it in GitHub Desktop.
Save gmcculloug/b95f24cb460a9fb6f1d6555004e1e332 to your computer and use it in GitHub Desktop.
Prints hierarchical view of Rails models
# active_record model descendant walker
def model
(ARGV.first || 'ApplicationRecord').classify.safe_constantize.tap do |model|
raise "Provide valid model name. Argv: #{ARGV.first}" unless model
raise "Model must be a sub-class of ActiveRecord::Base Argv: #{ARGV.first}" unless model < ActiveRecord::Base || model == ActiveRecord::Base
end
end
def base_model(model)
if model.superclass == ApplicationRecord || model == ApplicationRecord || model == ActiveRecord::Base
return model
end
return base_model(model.superclass)
end
def print_subclasses(model, prefix = "")
puts "#{prefix}#{model.name}"
model.descendants.sort_by(&:name).each { |m| print_subclasses(m, "#{prefix} ") if m.superclass == model }
end
silence_warnings { print_subclasses(base_model(model)) }
# model descendant walker
def print_subclasses(model, prefix = "")
puts "#{prefix}#{model.name}"
model.descendants.sort_by(&:name).each { |m| print_subclasses(m, "#{prefix} ") if m.superclass == model }
end
silence_warnings { print_subclasses(ARGV.first.classify.safe_constantize) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment