September 13, 2007
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 |
There’s something ironic about an error message that makes you laugh out loud.
So let’s just say you’re being a good developer and you’re writing tests. They are have good coverage (because you’re writing them first), they run fast, and you’ve setup a continuous integration (CI) server (like