10 March 2008 Manfred Stienstra and Sam Aaron

Ruby has dedicated keywords like if and else to define conditional logic. Other languages, like IO, use methods for conditional execution of code. Manfred shows how you can use a class in Ruby to do something similar.

Download episode

require "test/unit"

class Else
  def initialize(run)
    @run = run
  end
  
  def else
    yield if @run
  end
end

class Test::Unit::TestCase
  class << self
    def require_mocha
      require "rubygems"
      require "mocha"
      yield
      Else.new(false)
    rescue LoadError
      Else.new(true)
    end

    def needs_mocha
      require_mocha do
        yield
      end.else do
        puts "Please install mocha to run all the tests."
      end
    end
  end
end

class EigenTest < Test::Unit::TestCase
  needs_mocha do
    def test_truth
      truth = true
      truth.expects(:is_true?).returns(true)
      assert truth.is_true?
    end
  end
end