views:

504

answers:

6

What is the best way for me to determine a controller variable's value during execution?

For example, is there a way I can insert a break in the code, and cause the value of the variable to be output to the screen (or the log)?

+6  A: 

Yes. The easiest way is to raise the value as a string. Like so: raise @foo.to_s

Or, you can install the debugger (gem install ruby-debug), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction.

Inside the debugger prompt, you have many commands, including p to print the value of a variable.

Update: here's a bit more about ruby-debug.

Jordi Bunster
+4  A: 

If you have a controller instance variable named @foo, then in your controller you can simply do something like:

logger.debug "@foo is: #{@foo}"

Additionally, you can output the value in your view template using:

<%= debug @foo %>
John Topley
+5  A: 

I prefer using the inspect method like so:

raise @foo.inspect

It has more information than to_s, like the attribute values.

Jaryl
+1  A: 

Summary from Jordi Bunster, John Topley, and Jaryl:

I. Quick and dirty way:

raise @foo.inspect

in your controller. Or

<% raise @foo.inspect %>

in your view.

II. Proper logging to you development.log:

logger.debug "@foo == #{@foo.inspect}"

III. Full-fledged debugging:

Install the debugger (gem install ruby-debug), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction.

Inside the debugger prompt, you have many commands, including p to print the value of a variable.

squadette
A: 

Raising an exception is the fastest way if you just need to look at a value, but it's worth the time to learn how to use the debugger properly. It's rare that you would only need to just see the value of a variable, you are likely trying to find a bug in your code, and that's what a debugger is for.

Sending the info to the development log is slower than either of the other two options here so far if you learn how to use the debugger (who wants to read through log files). Use the logger for production, you are going to want to see what the value was when somebody calls you up and says everything is broken.

A: 

Well, I usually prefer the standard error output

$stderr.print("whatever")

Its simple and does the job.

liangzan