Skip to content

Instantly share code, notes, and snippets.

@jguitar
Created June 18, 2018 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jguitar/b0735f5e3fa2e4faac374c68bc237324 to your computer and use it in GitHub Desktop.
Save jguitar/b0735f5e3fa2e4faac374c68bc237324 to your computer and use it in GitHub Desktop.
Count all Rails models
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