Old Yeller: Finding Dead Code

» 04 Jul 2009

As Rails applications age, they tend to cruft up in ways that make maintenance difficult. Refactoring is the solution, and common best practices like unit testing and regular runs of "flog":http://ruby.sadi.st/Flog.html and"flay":http://ruby.sadi.st/Flay.html help facilitate this. Unfortunately, these techniques do not greatly help the elimination of dead code. Rails makes the accumulation of dead code, code that is never run in the application, very easy. Be it templates that are overridden by better, more format specific alternatives (e.g. @.html.erb@ vs. @.erb@), helper methods that are not excised when the views are changed, convenience methods on models that no longer reflect a use of the model, or controller actions for which no route exists, dead code confuses and complicates working with a code base. Refactoring a block of code that is never actually used is also an exercise in wasted frustration. To combat this, I have released "Old Yeller":http://github.com/schleyfox/old_yeller/tree/master. Using the power of RCov, Shoulda, Rails Routing, and hilarious monkey patching, Old Yeller will tell you what Ruby code is not run and which templates are never rendered. It automatically generates test cases for every rule in your routes and then runs the code. This creates an RCov coverage report for the application and a list of unused templates. !http://www.pixelmachine.org/images/oldyeller.jpg! h4. Caveats This tool is not perfect. For it to be effective, you must correctly configure parameters for your actions in @dead_code.rb@ and specify working data in your test fixtures. It is important to note that only routes that specify both controller and action will be run. Old Yeller is just too old to deal with catch-all routes or route precedence. It is important to note that code that is reported as not run, may actually be live code that gets called in some scenario that is not exercised by the test cases or test data. Code that is reported as being run is most certainly live. Before deleting code, use @ack@/@grep@ and common sense. Once again, the link is http://github.com/schleyfox/old_yeller/tree/master , tell your friends.