Sunday, April 4, 2010

Rails Code Stats gem

When rails 2.2 came out it added some syntactic sugar by implementing a declarative block syntax for tests. The syntax for this looks like this:

test "make sure something really critical happens" do
  #code that tests for something really critical

While this syntax update is great some of the tools that come with rails still haven't been updated to handle it nicely. The stats rake task which outputs basic code statistics such as lines of code and methods per class still doesn't count these tests. In the past I just copied the rake tasks code and made a new rake task that could handle the new syntax as well as the format shoulda uses. After I started playing around with rails 3 and figured out how to put rake tasks in a gem I decided to write a gem that would generate an improved stats output.

Introducing Rails Code Stats

For this gem I didn't just copy the code and slightly improve the output. I refactored the code to clean things up as well as making it easier to extend functionality. One of the main changes was separating the code that calculates the stats from the code that displays the stats. Currently it still just outputs to the command line, but I intend to add the ability to have it output a HTML version as well. In addition to the new test syntax introduced in rails 2.2, I also added support for shoulda's test syntax and improved the code so that it should be quite trivial to add support for another test method syntax. Installing this plugin is as easy as adding the following to your rails 3 applications Gemfile.

gem 'rails_code_stats'

I am contemplating suggesting to the rails core team as an alternative to the current rails stats task. It seems that it fits with where rails 3 is trying to go, if you can easily swap out DB persistance layers and javascript engines why not modularize the code statistics tool as well. Please comment if you have any suggestions on improving this gem.