Scourging your Ruby code with Flog

Flog is a tool build by Ryan Davis to analyze Ruby code complexity. It’s dead simple to run, and immediately provides useful metrics in the form of a “Flog score” per method. Don’t get too hung up on the actual values, but high outliers are prime candidates for refactoring.

I ran this on a couple recent projects I worked on, and it proved quite accurate in identifying the areas of code that seem to be in the most pain. Flog doesn’t replace hands-on code review, but it is still a helpful aid.

Below is a rake task I threw together for running Flog on a Rails project. Seems like a great candidate to install via Chris Wanstrath’s Sake, a system for handling Rake tasks that you want to be available from anywhere.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def flog(output, *directories)
  `find #{directories.join(" ")} -name \\*.rb|xargs flog > #{RAILS_ROOT}/tmp/flog/#{output}.txt`
end

desc "Flog models, controller, helpers and lib"
task :flog do
  flog "all", *%w[app/models app/controllers app/helpers lib]
end

namespace :flog do
  desc "Flog code in app/models"
  task :models do
    flog "models", "app/models"
  end
  
  desc "Flog code in app/controllers"  
  task :controllers do
    flog "controllers", "app/controllers"
  end
  
  desc "Flog code in app/helpers"  
  task :helpers do
    flog "helpers", "app/helpers"
  end
  
  desc "Flog code in lib"  
  task :lib do
    flog "lib", "lib"
  end
end

3 Responses to “Scourging your Ruby code with Flog”

  1. # Luke Melia Says:

    Cool, Bryan. You should add your sake task to sakebar [http://sakebar.railsrumble.com/]

  2. # Joshua Nichols Says:

    When I first ran this, I was getting: nichoj@metaverse ~/projects/technicalpickles.com $ rake flog (in /home/nichoj/projects/technicalpickles.com) rake aborted! No such file or directory – /home/nichoj/projects/technicalpickles.com/config/../tmp/flog/all.txt

    (See full trace by running task with --trace)

    So, in the flog method, we should be doing a mkdir. I added this bit to it: Dir.mkdir ”#{RAILS_ROOT}/tmp/flog”

    Worked like a charm after that.

    I wonder, do you think this is something that this is something that could be contributed back to flog?

  3. # Abhay Kumar Says:

    This is great. One small thing: you should probably check for the directory first before writing to a file in there.