Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the value of a controller variable during execution in Ruby on Rails?

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)?

like image 877
Brent Avatar asked Sep 13 '08 17:09

Brent


People also ask

How send data from controller view in Ruby on Rails?

Send Data from Controller to ViewOpen app/controllers/home_controller. rb file and modify it like below. And then, we need to modify the View file of the Action. Open app/views/home/index.

What does Before_action do in Rails?

When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.

What is the role of rails controller?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.

What are filters in rails?

Rails filters are methods that run before or after a controller's action method is executed. They are helpful when you want to ensure that a given block of code runs with whatever action method is called.


2 Answers

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.

like image 181
Jordi Bunster Avatar answered Sep 20 '22 01:09

Jordi Bunster


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 %>
like image 36
John Topley Avatar answered Sep 22 '22 01:09

John Topley