Created
June 18, 2018 15:58
-
-
Save jguitar/b0735f5e3fa2e4faac374c68bc237324 to your computer and use it in GitHub Desktop.
Count all Rails models
This file contains hidden or 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
class PrintCount | |
def diff | |
before = count_all_models_with_table | |
after = if block_given? | |
yield | |
count_all_models_with_table | |
else | |
Hash.new(0) | |
end | |
print_diff(before, after) | |
end | |
private | |
def models_with_table | |
ActiveRecord::Base.connection.tables.map do |x| | |
x.classify.safe_constantize | |
end.compact | |
end | |
def count_all_models_with_table | |
models_with_table.each_with_object(Hash.new(0)) do |klass, collection| | |
collection[klass.name] = if klass.respond_to? :with_deleted | |
klass.with_deleted.count | |
else | |
klass.count | |
end | |
end | |
end | |
def print_diff(before, after) | |
before.keys.each do |key| | |
next if before[key] == after[key] | |
diff = before[key] - after[key] | |
Rails.logger.warn("#{key}: #{diff}") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment