Fork me on GitHub

Rails Views, Spring Cleaning

2006-06-19

The way I do this is with a Rake task. Rake and Rails go so well together, and we already have a boatload of custom Rake tasks in our app, so it was an easy decision.

Basically, what I wanted was a quick way to see what helpers and actions weren’t being used. Just a simple list that I could use to help me find things that we probably didn’t need anymore.

So here it is:

Keep in mind this is NIX only (since that’s all I care about, currently), and is in no way comprehensive. Someone could easily make this pure-Ruby, safer, or simply more intelligent.

namespace :stale do
  task :helpers do
    stale_for_glob 'app/helpers/*_helper.rb'
  end
  task :actions do
    stale_for_glob 'app/controllers/*_controller.rb'
  end

  def stale_for_glob(glob)
    Dir[glob].each do |filename|
      File.open(filename) do |file|
        file.each do |line|
         if line =~ /^\s*def\s+([[:alnum:]_]+)/
           meth = $1
           if `grep -R '#{meth}' app vendor/plugins | grep -v svn`.strip.split("\n").size <= 1
             $stderr.puts "#{filename} : #{meth}"
           end
         end
        end
      end
    end
  end
end

What does this do? Well, it looks though the helper (or controller) files, and tries to find helpers (or actions) that are only defined and not used. Granted, it’s not flawless. If you have helpers or actions that have the same name and are defined in different files (not an edge case), there’ll be false negatives. You’ll also need to run it several times as you remove items, since one helper may only be called from another that you’ve removed. Don’t just rip out all the helpers (or actions) that show up in the results, either. Maybe they’re just not being used yet (and maybe they’re the hard work of your fellow developers, too).

Don’t forget to remove the test cases for anything you remove, too.

The point here is to dredge up old helpers and actions that, when you see them, will cause a lightbulb to go off over you head. Maybe you’ll exclaim, “Ah, I remember that piece of crap– I thought I got rid of that a month ago!”

Now really get rid of it. Shorter code is happier code.

If you’re developing a large Rails application, chances are you’re going to end up creating a lot of extra helpers and actions that fall into disuse– helpers are generally tightly coupled with views and often exist due to design decisions that end up changing over time, and actions can just as easily become obsolete.

This is a natural side-effect of long-term development. But you need to get rid of all that clutter; it affects your test statistics, it means more code to shuffle through to find things you are using– and it’s just plain ugly to keep around.

Discussion