Daily Code Reading #12 – Flay executable

This week I’m looking at some of the metrics libraries included in metric_fu. Since these libraries analyze Ruby code, I suspect that I’ll find some very interesting Ruby inside them.

I’m starting with flay, a library that analyzes code for duplication and structural similarities. Since flay includes a command line executable, I’m starting with that and will trace the application flow from there.

The Code

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/ruby
 
require 'flay'
 
flay = Flay.new Flay.parse_options
 
ARGV << '.' if ARGV.empty?
files = Flay.expand_dirs_to_files(*ARGV)
 
flay.process(*files)
flay.report

Review

Flay’s executable does five things to create a Flay report:

  1. Initializes a new Flay object by parsing command line options using optparse.
  2. Defaults the arguments to the current directory.
  3. Expands all directories to get a complete list of files.
  4. Processes the files.
  5. Outputs a report of the Flay results.

1. Initializes a new Flay object by parsing command line options using optparse.

optparse is a core Ruby class that helps to write Ruby scripts with command line options and flags. Flay is using this to set different options in Flay#parse_options.

2. Defaults the arguments to the current directory.

1
ARGV << '.' if ARGV.empty?

Flay is meant to be run as flay path/to/ruby.rb or flay lib/ and load all the Ruby files it can find. The code above also lets Flay have a default option of checking all files in the current directory, flay .. It’s pretty simple and I think I can use it in my own programs.

3. Expands all directories to get a complete list of files.

Flay#expand_dirs_to_files(*ARGV) has Flay recurse the file system to collect all Ruby files in nested sub-directories. This is just like having grep -R turned on.

4. Processes the files.

Flay#process is the core of Flay, where it checks and analyzes each file. I’ll be looking into it in more depth later this week, but this is where all the magic happens.

5. Outputs a report of the Flay results.

This just outputs a report on the command line with puts calls. Nothing fancy.

Now I see #expand_dirs_to_files and #process are the interesting parts of Flay that I’ll need to dig into next.