Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adds script to compute topological sort of Active Record models
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
require 'tsort' | ||
require 'set' | ||
|
||
class Graph < Hash | ||
include TSort | ||
|
||
alias tsort_each_node each_key | ||
|
||
def tsort_each_child(node, &block) | ||
fetch(node).each(&block) | ||
end | ||
end | ||
|
||
def children(model) | ||
Set.new.tap do |children| | ||
model.reflect_on_all_associations.each do |association| | ||
next unless [:has_many, :has_one].include?(association.macro) | ||
next if association.options[:through] | ||
|
||
children << association.klass | ||
end | ||
end | ||
end | ||
|
||
Dir.glob('app/models/**/*.rb') do |model| | ||
load model | ||
end | ||
|
||
graph = Graph.new | ||
ActiveRecord::Base.descendants.each do |model| | ||
graph[model] = children(model) unless model.abstract_class? | ||
end | ||
|
||
graph.tsort.reverse_each do |klass| | ||
puts klass.name | ||
end |