Debugger

之前在 application.html.erb 加了 debug 方法,在頁面上顯示一些資訊;在 Rails 4.2 ,增加了一個更直接的方式,透過 byebug gem 來幫助我們進一步的除錯。

要使用 byebug 方法,在 Users controller 加上程式碼:

app/controllers/users_controller.rb

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    debugger
  end

  def new
  end
end

現在瀏覽 /users/1,Rails server 就會顯示 byebug 的提示訊息:

(byebug)

這樣可以直接使用和在 console 的方式,來查詢 APP 的狀態或資訊:

(byebug) @user.name
"Example User"
(byebug) @user.email
"[email protected]"
(byebug) params[:id]
"1"

如果要離開提示訊息,繼續執行 APP,按 Ctrl-D,然後移除 show action 裡面的 debugger 程式碼:

.
.
def show
  @user = User.find(params[:id])
end