[英]How to debug using rails console and puts in application
我想通過rails控制台打開irb打印的一些線條。 我已經看到很多關於如何實現它的SO問題。 但是我沒有得到任何結果。
下面是代碼 -
def show
puts 'in show method'
@post = Feed.find_by_id params[:id]
puts @post.inspect
redirect_to root_path unless @post.present?
end
現在我已通過命令rails server
打開rails server
。 另外,在另一個終端我給命令rails console
,它打開了irb提示符。 在瀏覽器中我運行localhost:3000/posts/82
它會給出正確的帖子,但控制台中沒有顯示任何內容。 我錯過了什么步驟? 我想在調用特定方法時在控制台中打印一些東西。
調試的最佳方法是使用debugger
命令。
如果您使用的是ruby 2.0或更高版本,則必須使用gem 'byebug'
,如果您使用的是1.9或更低版本,那么gem ruby-debug
然后,當您在開發模式下運行服務器時,服務器將在到達debugger
時停止,允許您查看對象的狀態並對其進行修改(比僅使用puts
更好)
程序將停在服務器運行的同一窗口中。
一些基本命令:
有關調試的更多信息: http : //guides.rubyonrails.org/debugging_rails_applications.html
第line 2
的puts 'in show method'
將不會顯示rails console
的輸出。 相反,它顯示在您執行rails server
的同一終端中的輸出。 它們可能會因為輸出太多而丟失,所以試着在那里找到它。
Rails.logger.debug "in show method"
使用Rails.logger.debug "in show method"
等。 在終端尾部log / development.log中的第二個選項卡中
$ cd rails_app_root $ tail -f log/development.log
要么
$ cd rails_app_root $ less +F log/development.log
在那里,您將找到控制台的所有輸出。
嘗試使用Rails.logger
Rails.logger.info“我希望在開發日志中看到的一些調試信息.------#{@post.inspect}”
它將在日志文件中打印@post值。
我是一個大風扇puts
調試。 例如;
def index
method = Kernel.instance_method(:method)
p method.bind(request).call(:headers).source_location
@users = User.all
end
上面的代碼片段可以幫助您找到實現方法的位置:
Processing by UsersController#index as */*
["/Users/aaron/git/rails/actionpack/lib/action_dispatch/http/request.rb", 201]
你可以找到更冷靜puts
調試這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.