Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find unused helpers in a Rails app (slow)
#!/usr/bin/env ruby
#
# Shotgun approach (read: slow and dirty hack) to help find unused helpers in a Rails application
#
puts "Loading all source files into memory :("
source = {}
Dir["app/**/**/*.*"].each do |f|
source[ f ] = File.readlines( f )
end
puts "#{source.size} files loaded into memory"
helpers = []
source.keys.grep(/app\/helpers/).each do |f|
code = source[ f ]
code.each do |line|
if line =~ /def ([^\(\s]+)/
helpers << $1.chomp
end
end
end
puts "Scanning for #{helpers.size} helpers"
# combine the source code
complete_code = source.values.flatten
# Find occurances
helpers.each do |name|
found = false
complete_code.each do |line|
next if line =~ /def #{name}/
found = true if line =~ /#{name}/
end
puts "No traces found of #{name}..." unless found
end
@cheshire137

This comment has been minimized.

Copy link

cheshire137 commented Dec 3, 2012

I wish this was updated for Ruby 1.9. I get an invalid byte sequence in UTF-8 (ArgumentError) error on your line =~ /dev #{name}/.

@markoa

This comment has been minimized.

Copy link

markoa commented May 15, 2014

@moneypenny skipping asset files made me avoid it.

@tylerlee

This comment has been minimized.

Copy link

tylerlee commented Jan 30, 2015

Thanks for this. My hack amendment to make it work in Ruby 2.0 was

  complete_code.each do |line|
    next if line != 'UTF-8'
    next if line =~ /def #{name}/
    found = true if line =~ /#{name}/
  end
@kylefox

This comment has been minimized.

Copy link

kylefox commented Mar 28, 2019

I rewrote some of this to be much faster (about 80% faster in my case):

https://gist.github.com/kylefox/617b0bead5f53dc53a224a8651328c92

@cheshire137 As @markoa mentioned, you likely ran into the UTF errors while processing a binary file (i.e. a bitmap image). My update whitelists the file types to search, which avoids the UTF error and greatly speeds up the script overall.

@tylerlee FYI your change seems to cause every single helper to be flagged as unused because you're checking the line against the literal 'UTF-'8' string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.