Monthly Archives: March 2008

I’ve always enjoyed the ruby convention of using question marks to denote boolean methods. empty?, exist?, any?, alive?, etc… They’re concise and easy to read. I do have one gripe with it, sometimes testing the inverse makes my code read like yoda wrote it.


not sting.empty?
not path.file?
not param.blank?

In rails I use not something.blank? a lot, so creating a not_blank? method wrapper around blank? was a nice simple fix. But I’m lazy and easily give into the temptation of the dark side, so I created a Bizarro Object. Which lets me do this…


# Meaningless examples that prove my point

"".not.empty?       #=> false
"words".not.empty?  #=> true

0.not.zero?         #=> false
1.not.zero?         #=> true

And here is the bit of code that makes it work…


class BizarroObject
  # Since this is a proxy, get rid of every default method
  # Copied from Jim Weirich's BlankSlate class
  # http://onestepback.org/index.cgi/Tech/Ruby/BlankSlate.rdoc
  instance_methods.each { |m| undef_method m unless m =~ /^__/ }

  # Takes an object as a parameter and will invert the return values of all it's methods.
  def initialize(object)
    @object = object
  end

  def method_missing(symbol, *args)
    !@object.send(symbol, *args)
  end
end

class Object
  # This is where the proxy/bizarro object is created
  def not
    BizarroObject.new(self)
  end
end

It’s not optimized, and it’s a little ridiculous, but I love that ruby lets me abuse it like this.

I have a rails project that is too wily for autotest, but I still want a simple way to make sure my tests are passing. Using git hooks is a simple solution to this problem.

Git Hooks?
Hooks (more info here) are little scripts that git triggers after certain commands. They are located in your projects GIT_DIR/hooks directory and are disabled by default. To enable them just chmod +x the hook you want to run.

How is this helpful for testing?
You can run your specs from the GIT_DIR/hooks/pre-commit hook! The script is run every time you call git commit. If the script exits with a non-zero status your changes won’t be committed and you can scurry to fix your specs. Here is a little example of how I’m using in one of my apps


#!/usr/bin/env ruby

html_path = "spec_results.html"

`spec -f h:#{html_path} -f p spec` # run the spec. send progress to screen. save html results to html_path

# find out how many errors were found
html = open(html_path).read
examples = html.match(/(\d+) examples/)[0].to_i rescue 0
failures = html.match(/(\d+) failures/)[0].to_i rescue 0
pending = html.match(/(\d+) pending/)[0].to_i rescue 0

if failures.zero?
  puts "0 failures! #{examples} run, #{pending} pending"
else
  puts "\aDID NOT COMMIT YOUR FILES!"
  puts "View spec results at #{File.expand_path(html_path)}"
  puts
  puts "#{failures} failures! #{examples} run, #{pending} pending"
  exit 1
end