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


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?


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


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?


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


you can use abort with inspect

abort params[:whatevs].inspect  


abort @my_variable.inspect  

for JSON format

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


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
Next Post »