Skip to content

Instantly share code, notes, and snippets.

@Kallin
Created February 27, 2023 14:45
Show Gist options
  • Save Kallin/93f2110333bd591b3d9384382f4b67d0 to your computer and use it in GitHub Desktop.
Save Kallin/93f2110333bd591b3d9384382f4b67d0 to your computer and use it in GitHub Desktop.
callback_scanner.rb
CALLBACKS = [
'before_validation',
'after_validation',
'before_save',
'around_save',
'before_create',
'around_create',
'after_create',
'after_save',
'after_commit',
'after_rollback',
'before_validation',
'after_validation',
'before_save',
'around_save',
'before_update',
'around_update',
'after_update',
'after_save',
'after_commit',
'after_rollback',
'before_destroy',
'around_destroy',
'after_destroy',
]
def find_callback_counts(dir_path, extension)
callback_counts = Hash.new(0)
Dir.glob(File.join(dir_path, "*")).each do |file|
if File.directory?(file)
find_callback_counts(file, extension)
elsif File.extname(file) == extension
# count the number of times each callback shows up in the file
file_content = File.read(file)
CALLBACKS.each do |callback|
count = file_content.scan("#{callback} :").length
callback_counts[file] += count if count > 0
end
end
end
callback_counts.each do |callback, count|
puts "#{callback}: #{count}"
end
end
# example usage
find_callback_counts(".", ".rb") # searches the current directory for Ruby files with Rails callbacks, and counts the number of times each callback shows up
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment