开发者

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 ret开发者_如何学Gourn 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

or

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 Cmd k to clear the whole screen buffer first, and use the browser to fetch a webpage, and now use Cmd f to search for the string you printed out, and it works quite well also. Actually if Cmd k is used to first clear the whole screen buffer, then the print out should always fit in the screen buffer.

Update: With Rails 3.x, we can make use of flash.error, flash.notice, flash.now.notice to print out something in the view if we want to: https://www.rubyguides.com/2019/11/rails-flash-messages/

Example:

flash.notice = "DEBUG INFO: some_obj is #{some_obj.inspect}"


In the controller:

 render json: @some_object
 return

It will show the object as JSON directly in the browser and stop execution. You can use some browser extensions like JSONView for Chrome to prettify the JSON in the browser.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜