Skip to content

Instantly share code, notes, and snippets.

@kylefox
Forked from kennethkalmer/find_unused_helpers.rb
Created March 28, 2019 21:49
Show Gist options
  • Save kylefox/617b0bead5f53dc53a224a8651328c92 to your computer and use it in GitHub Desktop.
Save kylefox/617b0bead5f53dc53a224a8651328c92 to your computer and use it in GitHub Desktop.
Find unused helpers in a Rails app
#!/usr/bin/env ruby
#
# Shotgun approach (read: slow and dirty hack) to help find unused helpers in a Rails application
#
start = Time.now
# Build an array of filename globs to process.
# Only search file types that might use or define a helper.
extensions = %w[rb js haml erb jbuilder].map { |ext| "app/**/**/*.#{ext}" }
# Build a hash of all the source files to search.
# Key is filename, value is an array of the lines.
source_files = {}
Dir.glob(extensions).each do |filename|
source_files[filename] = File.readlines(filename)
end
# Build an array of method names defined in app/helper/* files.
helpers = source_files.keys.grep(/app\/helpers/).map do |filename|
source_files[filename].map do |line|
Regexp.last_match(1).chomp if line =~ /def ([^\(\s]+)/
end
end.flatten.reject(&:nil?)
puts "Scanning #{source_files.size} files for #{helpers.size} helpers..."
# Combine all the source code into a giant array of lines.
source_code = source_files.values.flatten
# Iterate over all the helpers and reject any that appear anywhere in the complete source.
unused = helpers.reject do |helper|
source_code.any? do |line|
line.match?(/#{helper}/) && !line.match?(/def #{helper}/)
end
end
finish = Time.now
if unused
puts "\nFound #{unused.size} unused helpers:\n\n"
unused.each { |helper| puts " - #{helper}" }
puts "\n"
else
puts 'No unused helpers were found.'
end
puts "Finished in #{finish - start} seconds."
@jjf21
Copy link

jjf21 commented Sep 28, 2021

Thanks, it saved me a lot of time !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment