Switching code in or out

ie. I want all checks on maximum when I run the unit tests, I want
them all switched off (compiled out) when I'm running the two hour
long deep thought, and I want them selectively switched on when it
crashes half way through the big run. eg. All the precond checks on.

Here's a very rough way of doing this. It rewrites the methods at load
time to explicitly call the pre and post conditions.

module Awesome
  module ClassMethods
    def precondition func, prefunc
      class_eval %{
        alias :old_pre_#{func} :#{func}
        def func *a, &b
          #{prefunc} *a, &b
          old_pre_#{func} *a, &b
        end
      }
    end

    def postcondition func, postfunc
      class_eval %{
        alias :old_post_#{func} :#{func}
        def func *a, &b
          ret = old_post_#{func} *a, &b
          #{postfunc} ret, *a, &b
          ret
        end
       }
    end
  end

  def self.append_features m
    super
    m.extend ClassMethods
  end
end

To use it:

class A
  include Awesome

  def pre; puts "pre called"; end

  def post x; puts "post called with return value #{x}"; end

  def func
    puts "func called"
    3
  end

  if $DEBUG
    precondition :func, :pre
    postcondition :func, :post
  end
end

a = A.new
a.func

People have written much nicer pre and post hook frameworks, I think
under the moniker AOP (?). But this should get you started.

···

--
William <wmorgan-ruby-talk@masanjin.net>