Reputation: 16839
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)?
Upvotes: 8
Views: 9052
Reputation: 6352
gem 'pry-moves'
binding.pry
where you want to stopThen continue by typing c
, move to next line with n
or perform other debugging actions until you will resolve the issue.
Upvotes: 0
Reputation: 6904
Well, I usually prefer the standard error output
$stderr.print("whatever")
Its simple and does the job.
Upvotes: 0
Reputation:
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.
Upvotes: 0
Reputation: 8286
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.
Upvotes: 3
Reputation: 2601
I prefer using the inspect method like so:
raise @foo.inspect
It has more information than to_s, like the attribute values.
Upvotes: 5
Reputation: 115322
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 %>
Upvotes: 6
Reputation: 4906
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.
Upvotes: 11