Skip to content

Commit

Permalink
Adds script to compute topological sort of Active Record models
Browse files Browse the repository at this point in the history
  • Loading branch information
rcristal committed Dec 12, 2017
1 parent 1135faa commit 9604014
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions script/topological_sort_models.rb
@@ -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

0 comments on commit 9604014

Please sign in to comment.