Monthly Archives: June 2009


SexpPath is a ruby DSL for pattern matching S-Expressions. Think of it as XPath or Regular Expressions for Ruby code, and you’re most of the way there.

Here is an example of an S-Expression in Ruby:

pets = s(:pets, 
  s(:cat, :fluffy, s(:color, :white)),
  s(:cat, :snuggles, s(:color, :grey)),
  s(:fish, :bubbles, s(:drinks, :water)

This query extracts all the cats from our example:

pattern = Q?{ s(:cat, atom, _ ) }
cats = pattern

The SexpPath query above looks for expressions that start with the symbol :cat. The atom part says that we will match any symbol, so in the example above it would match both :fluffy and :snuggles. The underscore at the end will match anything at all, in this case, the S-Expression for color.

You can also match nested expressions with SexpPath:

pattern = Q?{ s(:cat, atom, s(:color, grey) ) }
grey_cats = pattern

SexpPath also has a notion of named matches. This query will place each cat’s name in the query result:

pattern = Q?{ s(:cat, atom % 'name', _ ) }
cat_matches = pattern
cat_names ={|match| match['name']}

The % operator tells SexpPath where to stash a matching value.

Here is an example of using SexpPath with Ryan Davis’ excellent ParseTree library to extract all the methods in a given file:

# read in a ruby file
code ='pony_factory.rb')
# parse the file with ParseTree
sexp = Sexp.from_array(
# create a SexpPath to find all the methods
pattern = Q?{ s(:defn, atom % 'name', _ ) }
# print all the methods in the ruby file do |match|
  puts match['name']

Now you’re doing static analysis on Ruby code! To learn more take a look at the Readme on GitHub, or skim over some of the examples.

If you have any suggestions or critiques of the code, API, etc. I would love to hear from you so comment, fork, or open an issue on GitHub.


Filed under ruby, ruby_diff, Uncategorized

Excel ruby-prof Report Printer

I got tired of re-sorting ruby-prof‘s profiles in TextMate ( sort -n -r -k 2 is neat, but cumbersome ). So I whipped up a little gem for printing out the reports as Excel documents with excel_printer.

If nothing else, it’s a nice example of using the Spreadsheet gem in ruby.

Go fork it on Github and do something neat with it.-

Leave a comment

Filed under Uncategorized

OpenGem 1.3.1

Quick note, I just updated OpenGem so that you can now do:

gem read activerecord

If you the rdoc has not been generated yet, OpenGem will generate it for you and then open it up for your browsing pleasure (or horror).

So go ahead and update.

sudo gem update open_gem

Leave a comment

Filed under Uncategorized