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
Just need to convince O'Reilly to actually publish it...