Featurizing debug()

Raility Checkers:

Everyone needs a little debug() now and then. The RHTML statement <%=
debug(x) %> will barf out the value of x into the output page, inside
a tasteful grey DIV.

Suppose x were a complex expression. Or suppose (quell horror!) we
have several debugs, and they come and go.

Suppose I wanted debug() to also report the expression. debug(x + 1)
would emit x + 1: 43.

How to do that in Ruby?

(I could do it trivially in >cough< C++…)


Phlip
http://c2.com/cgi/wiki?ZeekLand ← NOT a blog!!

Well, you do it pretty much the way you would in >cough< C++:

irb(main):001:0> def debug(exp)
irb(main):002:1> puts “#{exp} : #{eval(exp)}”
irb(main):003:1> end
=> nil
irb(main):004:0> debug(‘3+2’)
3+2 : 5
=> nil
irb(main):005:0>

Rember the C and C++ preprocessors only deal with strings, so when you
use
#define you’re just doing some string substitution wherever the macro
appears in your >cough< code. The actual expressions are not evaluated
until
later (ok, ok, some preprocessors are smart enough to fold simple
invariant
expressions).

Does the above implementation of debug work for you?

Phlip wrote:


View this message in context:
http://www.nabble.com/-Rails--featurizing-debug()-tf2641121.html#a7372543
Sent from the RubyOnRails Users mailing list archive at Nabble.com.

You need to pass in a binding to introduce context into the eval.

A small bit of info can be found here:

module Kernel - RDoc Documentation

V/r
Anthony

On 11/16/06, Phlip [email protected] wrote:


Email: [email protected]
Cell: 808 782-5046
Current Location: Melbourne, FL

s.ross wrote:

irb(main):001:0> def debug(exp)
irb(main):002:1> puts “#{exp} : #{eval(exp)}”
irb(main):003:1> end

irb(main):004:0> debug(‘3+2’)
3+2 : 5

Does the above implementation of debug work for you?

Wouldn’t the eval() miss the scope of the calling function?

(If you can keep a secret, I still haven’t figure out how to pass
scope, continuances (?), and locals into eval()…)


Phlip