ruby-debug命令

  轉自http://hlee.javaeye.com/blog/361405

本篇主要是爲了說明如何進行Rails調試的.但ruby-debug本身不是Rails的插件,也就是說ruby-debug是調試ruby程序.
1. 安裝ruby-debug
那麼,安裝自然,就不是Rails的插件安裝,下載gem包,或者直接gem安裝如下:

gem install ruby-debug -y  

2. 在rails中如何配置
修改環境配置文件:

# config/environments/development.rb 
config.breakpoint_server = true
require "ruby-debug"

 

增加斷點
在需要調試的代碼部分增加debugger

def new
  @story = Story.new(params[:story])   
  @story.user = @current_user
  if request.post? and @story.save   
    debugger   
    @story.tag_with params[:tags] if params[:tags]   
    flash[:notice] = "Story submission succeeded"
    redirect_to :action => 'index'
  end
end

 

啓動運行

Ruby代碼

  1. ruby script/server -e development 


調試運行界面

基本命令詳解

1. help

第一個,最重要的命令

(rdb:5) help  
ruby-debug help v0.10.3  

 

你可以用help cmd看cmd命令的內容詳情
這裏說明我的ruby-debug是0.10.3版.這個版本的一些命令已經和之前版本的命令差很多了.


2. list
用來瀏覽代碼列表和目前斷點的位置

(rdb:2) list  
[54, 63] in ./script/../config/../app/controllers/user_controller.rb  
   54      end
   55    end
   56    
   57    def login  
   58      debugger  
=> 59      user = User.auth(@params['login'], @params['pwd'])  
   60      if user  
   61        @session[USER_PARAM] = user  
   62        set_filter(user)  
   63      else

多次打list可以看下面的代碼.

l[ist]          #列出當前代碼,再次輸入,列出後面代碼
l[ist] -        #列出當前代碼,往前的代碼
l[ist] =        #列出當前行代碼
l[ist] nn-mm    #列出給定行的代碼

3. where
用於查看當前程序運行的堆棧情況

(rdb:2) where  
--> #1 ./script/../config/../app/controllers/user_controller.rb:59:in `login'
#2 /usr/.../action_controller/base.rb:910:in `perform_action_without_filters'
#3 /usr/.../action_controller/filters.rb:368:in `perform_action_without_benchmark'
#4 /usr/.../action_controller/benchmarking.rb:69:in `measure'
#5 /usr/.../action_controller/benchmarking.rb:69:in `perform_action_without_rescue'
#6 /usr/.../action_controller/rescue.rb:82:in `perform_action'
    ...  

4. up/down
使用up和down命令可以在之前的where顯示的堆棧中進行調試.並可以結合list和察看變量的方法,進行動態的調試.
如下:

(rdb:2) up 2  
#3 /usr/.../action_controller/filters.rb:368:in `perform_action_without_benchmark'
(rdb:2) l  
[363, 372] in /usr/.../action_controller/filters.rb  
   363    
   364        def perform_action_with_filters  
   365          before_action_result = before_action  
   366    
   367          unless before_action_result == false || performed?  
=> 368            perform_action_without_filters  
   369            after_action  
   370          end
   371    
   372          @before_filter_chain_aborted = (before_action_result == false)  
(rdb:2) before_action_result  
[:verify_login, :verify_access]  
(rdb:2) performed?  
false
(rdb:2) down 2  

5. step/next

s[tep][+-]?[ nnn]         
#nnn 表示次數
#'+' 強制向其它線程
#'-' 和上面相反並且禁用掉force_stepping setting.

單步執行,使用next命令向下執行而不進入命令本身.這兩個都支持一個數字的參數表明執行多少:

(rdb:2) s  
script/../config/../app/models/user.rb:27:    find :first,   
(rdb:2) l  
[22, 31] in script/../config/../app/models/user.rb  
   22    def status_name  
   23      STATUS_NAMES[self.status]  
   24    end
   25    
   26    def self.auth(login, pwd)  
=> 27      find :first,   
   28        :conditions => ["login = ? AND pwd = ? AND status = ?",   
   29                      login, pwd, ACTIVE]  
   30    end
   31    
   32    def is_admin?  

6. Thread

th[read] l[ist]                # 列出所有的線程
th[read] stop             # 停止指定線程
th[read] resume           # 恢復指定線程
th[read] [sw[itch]]       # 切換執行環境到指定線程
th[read] [cur[rent]]           # 顯示當前線程

用列出和切換線程,示例如下:

(rdb:2) thread list  
 1 # /usr/local/lib/ruby/1.8/webrick/server.rb:91
+2 # script/../config/../app/models/user.rb:27
 31 # /usr/local/lib/ruby/1.8/drb/drb.rb:944
(rdb:2)  
By the way, the debugger prompt also shows the current thread number (rdb:2).  

7. var

v[ar] cl[ass]                   #顯示當前上下文的所有類變量
v[ar] c[onst] #顯示當前上下文的常數對象 v[ar] g[lobal] #顯示當前上下文的全局變量 v[ar] i[nstance]#顯示當前上下文的當前對象的實例變量 v[ar] l[ocal] #顯示當前上下文的所有局部變量

 

這個命令相當的強大,比起breakpoint的params來說,也是經常用到的.顯示當前上下文的變量參數情況.例子如下:

(rdb:2) var local  
  login => "admin"
  pwd => "letmein"
(rdb:2) var global  
  $! => nil
  $" => ["rubygems.rb", "rbconfig.rb", "rubygems/rubygems_version.rb",   
...  

8. breakpoint

b[reak] file:line [if expr] #在expr的條件下,設在文件的第幾行設置斷點
b[reak] class(.|#)method [if expr] #在expr成立條件下,設置斷點在類的方法下

在特點條件的斷點,也是很方便的地方.示例如下:

#以下代碼由夜鳴豬@javaeye奉獻
(rdb:1) l #list的簡寫,顯示當前位置
   26      #breakpoint
   27      @current_item = @cart.add_product(product)  
   28      debugger  
=> 29        respond_to do |format|  
   30          format.js if request.xhr?  
   31          format.html {redirect_to_index}  
   32        end
   33    rescue ActiveRecord::RecordNotFound  
(rdb:1) where  
--> #0 StoreController.add_to_cart
       at line D:/RORWS/depot_t/app/controllers/store_controller.rb:29  
Warning: saved frames may be incomplete; compare with caller(0).  
(rdb:1) b 30 #在第30行設置斷點
Breakpoint 1 file D:/RORWS/depot_t/app/controllers/store_controller.rb, line 30  
(rdb:1) c #continue的縮寫,推出debug環境執行
Breakpoint 1 at store_controller.rb:30 #斷點調試,中斷了
D:/RORWS/depot_t/app/controllers/store_controller.rb:30  
format.js if request.xhr?  
(rdb:1) l #再看一下位置
[25, 34] in D:/RORWS/depot_t/app/controllers/store_controller.rb  
   25      product = Product.find(params[:id])  
   26      #breakpoint
   27      @current_item = @cart.add_product(product)  
   28      debugger  
   29        respond_to do |format|  
=> 30          format.js if request.xhr?  
   31          format.html {redirect_to_index}  
   32        end
   33    rescue ActiveRecord::RecordNotFound  
   34      logger.error("Attempt to access invalid product #{params[:id]}")  
(rdb:2) b 72 if params['user'] == 'admin' #在admin的條件下設置斷點
Set breakpoint 1 at ./script/.../controllers/user_controller.rb:69  
To list all breakpoints use break command without parameters:  
(rdb:1) info break # 顯示當前都設置了什麼斷點
Num Enb What  
  1 y   at store_controller.rb:30  
        breakpoint already hit 1 time  

9. continue
這個簡單繼續執行

(rdb:2) cont  
127.0.0.1 - - [11/07/2006:15:09 EDT] "POST /user/login HTTP/1.1" 302 96  
http://localhost:3000/bug/list -> /user/login  
127.0.0.1 - - [11/07/2006:15:12 EDT] "GET /bug/list HTTP/1.1" 200 3830  
http://localhost:3000/bug/list -> /bug/list  

10. delete

del[ete][ nnn...]       #刪除指定或者所有breakpoints

11. save

save [FILE]  

將當前debugger的狀態保存成爲文件,保存的狀態,包括所有設定breakpoints,設定, 捕獲的斷點.不寫文件名會假定生成一個.
使用source命令,得到相關信息.
12. catch

cat[ch]          #等同與 "info catch"
cat[ch]       #攔截所指定的異常

13. backtrace

bt|backtrace            #where - display的別名
(rdb:8) backtrace  
--> #0 StoreController.add_to_cart
       at line D:/RORWS/depot_t/app/controllers/store_controller.rb:29  
#1 Kernel.send
       at line c:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253  
#2 ActionController::Base.perform_action_without_filters
       at line c:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253  
#3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
       at line c:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617  

顯示所有堆棧的執行信息.使用"up" and "down" 可以調試和改變在堆棧的執行.當前的位置使用-->符號表明.

14. edit
修改特定文件.如果沒有任何參數,則顯示當前最近修改的行.用FILE:LINENUM的格式指定修改的文件和行號.以便一即使修改

15. quit

q[uit] [unconditionally]        #從調試環境推出.
exit    #就是quit命令的別名

通常情況下,退出之前會有,確認提示. 然而,如果quit命令使用了參數"unconditionally",將不會有提示信息.

16. set
設定ruby-debug的環境,Boolean變量可以設定爲on off或者1 0.設定變量可以用show顯示

set annotate # 設定註釋等級
set args # 設定變量列表,用來傳遞給運行環境
set autoeval # 在不能直接輸出的表達式,進行eval計算
set autolist # 在每個breakpoint時執行list
set autoirb # 任何時候只要stop則執行irb
set autoreload # 當代碼有修改的時候,從新load
set basename # 設定basename只顯示文件名
set callstyle # 設定顯示變量格式
set debuggertesting # 用於測試debugger自身
set forcestep # 保證'next/step'命令總是能向新行移動
set fullpath # 在frames中顯示文件的完整路徑名
set history # Generic command for setting command history parameters
set keep-frame-bindings # Save frame binding on each call
set linetrace+ # Set line execution tracing to show different lines
set linetrace # Set line execution tracing
set listsize # Set number of source lines to list by default
set trace # Display stack trace when 'eval' raises exception
set width # Number of characters the debugger thinks are in a line

17. info
顯示相關信息

info args # Argument variables of current stack frame
info breakpoints  # 顯示當前所有斷點的狀態
info catch # 可以被捕獲的Exceptions,通過catch命令設定
info display  # 程序結束時的輸出
info file # 關於讀取文件的內容
info files # 關於讀取文件的時間和名字等信息
info global_variables # 所有全局變量
info instance_variables # 當前frame的示例變量
info line # 當前文件的當前行有關信息
info locals # 局部變量信息
info program # 程序執行狀態信息
info stack # 相關stack信息
info thread # Thread相關信息
info threads # Thread相關信息
info variables # 局部變量示例變量信息

18. show

show annotate # 顯示註釋級別
show args # 顯示當程序要執行時的參數列表
show autoeval # 是否顯示當遇到不識別命令
show autolist # 顯示是否自動list的設定
show autoirb # 顯示是否有設定autoirb
show autoreload # 顯示是否有設定autoreload
show basename # Show if basename used in reporting files
show callstyle # Show paramater style used showing call frames
show commands # Show the history of commands you typed
show forcestep # Show if sure 'next/step' forces move to a new line
show fullpath # Show if full file names are displayed in frames
show history # Generic command for showing command history parameters
show keep-frame-bindings # Save frame binding on each call
show linetrace # 顯示行執行信息
show linetrace+ # Show if consecutive lines should be different are shown in tracing
show listsize # Show number of source lines to list by default
show port # Show server port
show post-mortem # Show whether we go into post-mortem debugging on an uncaught exception
show trace # Show if a stack trace is displayed when 'eval' raises exception
show version # 顯示debug版本號
show width # 顯示調試信息的行字數

19. condition

Condition breakpoint-number expression  

給特定的brakepoint添加,執行條件.如果,expression爲空,那麼斷點執行的約束,取消


20. eval

e[val] expression   #    計算表達式的值並輸出
#    可以做爲p別名.

* 提示 - 如果,想要設定爲自動調用eval進行,表達式計算.需要設定autoeval 使用命令

use 'set autoeval'

21. reload

r[eload]        forces source code reloading  

22. ps

ps expression   #計算數組,集合,序列,表達式組的值,並序列化輸出

23. undisplay

undisp[lay][ nnn]  

取消一些表達式的輸出

引用

Arguments are the code numbers of the expressions to stop displaying.
No argument means cancel all automatic-display expressions.
"delete display" has the same effect as this command.
Do "info display" to see current list of code numbers.

24. irb

irb    # 打開一個(IRB) 環境

25. finish

fin[ish] [frame-number] #Execute until selected stack frame returns.

引用

If no frame number is given, we run until the currently selected frame
returns.  The currently selected frame starts out the most-recent
frame or 0 if no frame positioning (e.g "up", "down" or "frame") has
been performed. If a frame number is given we run until that frame
returns.

累了,假裝寫完了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章