Skip to content

Instantly share code, notes, and snippets.

Forked from kennethkalmer/find_unused_helpers.rb
Created March 28, 2019 21:49
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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 =
# 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)
# 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]+)/
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}/)
finish =
if unused
puts "\nFound #{unused.size} unused helpers:\n\n"
unused.each { |helper| puts " - #{helper}" }
puts "\n"
puts 'No unused helpers were found.'
puts "Finished in #{finish - start} seconds."
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