Created
August 3, 2018 12:36
-
-
Save gmcculloug/b95f24cb460a9fb6f1d6555004e1e332 to your computer and use it in GitHub Desktop.
Prints hierarchical view of Rails models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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