Rakefile snippet to run Rails’ rake:stats in a plain old gem
11 08 2008I’ve been moving a bunch of utility code out of a medium sized project (>10KLOC) to make it easier to test. I started by trying to make a set of plugins, but inter-plugin dependency management is basically nonexistent, and now that Rails supports explicit Gem dependencies, I decided to make them gems.
I’m happy I chose to make them gems, but I miss some of the stuff you get in a Rails project. In particular I wanted ‘rake:stats’, so I can update my estimation spreadsheet which is now almost 9 months old. I need the stats for each gem in addition to the main Rails project, in order to compare this to prior figures from the Rails project before I split it up.
So, here is the Rakefile snippet that I added, which adds the rake:stats task into a regular gem. If you don’t have the Rails gem installed, it will fail gracefully, without breaking your whole gem. So you need not make your teeny little gem depend on all of Rails being installed on every machine where your gem needs to go. Just install Rails whereever you want to run stats, which is probably already the case on your development machine.
Here is a Pastie link, since my blog theme truncates the too-wide text: this same code on Pastie
# stats
begin
gem 'rails'
require 'code_statistics'
namespace :spec do
desc "Use Rails's rake:stats task for a gem"
task :statsetup do
class CodeStatistics
def calculate_statistics
@pairs.inject({}) do |stats, pair|
if 3 == pair.size
stats[pair.first] = calculate_directory_statistics(pair[1], pair[2]); stats
else
stats[pair.first] = calculate_directory_statistics(pair.last); stats
end
end
end
end
::STATS_DIRECTORIES = [['Libraries', 'lib', /.(sql|rhtml|erb|rb|yml)$/],
['Tests', 'test', /.(sql|rhtml|erb|rb|yml)$/]]
::CodeStatistics::TEST_TYPES << "Tests"
end
end
desc "Report code statistics (KLOCs, etc) from the application"
task :stats => “spec:statsetup” do
CodeStatistics.new(*STATS_DIRECTORIES).to_s
end
rescue Gem::LoadError => le
task :stats do
raise RuntimeError, “‘rails’ gem not found - you must install it in order to use this task.n”
end
end
BTW I intend to replace this with a sloccount-based task later. If and when I do that I’ll publish it here.





