How to determine the value of a controller variable at runtime in Ruby on Rails?

What is the best way to determine the value of a controller variable at runtime?

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

+6
variables debugging ruby ruby-on-rails
source share
6 answers

Yes. The easiest way is to increase the value as a string. For example: 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 statement.

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

Update here a little more about ruby-debug .

+11
source share

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

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

Alternatively, you can display the value in your view template using:

 <%= debug @foo %> 
+5
source share

I prefer to use the verification method as follows:

 raise @foo.inspect 

It has more information than to_s as attribute values.

+5
source share

Summary from Jordi Banster, John Topley and Jaril:

I. Quick and dirty way:

 raise @foo.inspect 

in your controller. Or

 <% raise @foo.inspect %> 

in your view.

II. Proper login to development.log :

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

III. Full 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 statement.

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

+3
source share

Raising an exception is the fastest way if you just need to look at the value, but you should take the time to learn how to use the debugger correctly. It’s rare that you just need to see the value of a variable, you are probably trying to find an error in your code, and why you need a debugger.

Sending information to the development log is slower than either of the other two options if you learn how to use the debugger (who wants to read the log files). Use a logger for production, you will want to know what this value is when someone calls you and says that everything is broken.

0
source share

Well, I usually prefer standard error output

$ stderr.print ("all")

Simple and works.

0
source share

All Articles