Brian's Waste of Time

Wed, 06 Apr 2005

Ruby Metaprogramming 201

If you find yourself doing a lot of eval(..) based metaprogramming, remember to include debug stuff!

begin
    eval("dsadh!!sadkhj how are you today?")
rescue Exception => e
    log.error "Metaprogramming error [#{e}]"
end

Which is nifty and all if the eval fails, but what happens on the way more subtle?

begin
  eval <<-EOM
    def foo
      robert is sick today
    end
  EOM
rescue Exception => e
  log.error "Metaprogramming error [#{e}]"
end

Where you don't get the syntax problem until you invoke foo. Solution!

eval <<-EOM
  def foo
    begin
      robert is sick today
    rescue Exception => e
      puts "Error while invoking foo defined from [insert stuff to help you debug]: \#{e}"
    end
  end
EOM 

You cannot catch syntax errors, but because so much of ruby uses ruby this isn't a big deal most of the time =) Note escaping the hash in \#{e} -- this is important because just #{e} would fail. Why is an exercise left to the reader ;-)

4 writebacks [/src/ruby] permanent link

When April Fishes Go Bad

Just need to convince O'Reilly to actually publish it...

0 writebacks [/src/lisp] permanent link