Tutorial :On Ruby on Rails, how do we print debug info inside of a controller?



Question:

In PHP, CGI, or in RoR's View, we can easily print out debug information. How about in the Controller, how can we just say, print "hello world" (to the webpage output) and return to continue with the view, or stop the controller right there?


Solution:1

In the controller you can:

render :text => @some_object.inspect  

But your view won't be rendered.

You could also:

Rails.logger.debug("My object: #{@some_object.inspect}")  

and run tail on log/development.log to see the output.

In the view the recommeneded way is:

<%= debug(@some_object) %>  


Solution:2

Don't know about print, but puts never failed me. Your hello world will be in console and logs and normal flow will continue.
Did I understand you correctly?


Solution:3

You can debug in the view: <%= debug @post %>. More info: http://guides.rubyonrails.org/debugging_rails_applications.html


Solution:4

you can use abort with inspect

abort params[:whatevs].inspect  

or

abort @my_variable.inspect  

for JSON format

render json: JSON.pretty_generate(JSON.parse(@my_variable.to_json))  


Solution:5

Actually, Nikita's suggestion isn't bad. But usually it is hard to look at the data in the terminal because the screen buffer size can be limited and it is full of previous data from previous rendering of pages.

But, say on the Mac, just make sure the screen buffer is large enough, and also use in the rails server terminal the key Command k to clear the whole screen buffer first, and use the browser to fetch a webpage, and now use Command f to search for the string you printed out, and it works quite well also. Actually if Command k is used to first clear the whole screen buffer, then the print out should always fit in the screen buffer.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »