`

ruby-debug 基本使用

阅读更多
Posted on July 11, 2006
本文内容有些陈旧,部分命令过期,请点击这里参见最新版的Rails的调试 ruby-debug 安装使用和命令详解

Installation

The installation procedure requires rubygems package and C compiler available.

Two notes worth to mention:

  • For Debian users, you must have ruby-dev package installed.
  • For Windows users, I don't have a precompiled version for Windows available yet.

The installation procedure is very simple:

    $ sudo gem install ruby-debug

Basic usages

There are two way you can use this library.

rdebug script.

When you start your application with rdebug script, the debugger is activated by default and the execution of your script is halted at the first line of code:

$ cat test.rb 
puts 'ok'

$ rdebug test.rb 

./test.rb:1:puts 'ok'
(rdb:1) list
[-4, 5] in ./test.rb
=> 1  puts 'ok'
(rdb:1)

From this point you can invoke any commands available, such as you can create breakpoints and step through your code.

On demand invocation

You can require ruby-debug library from inside of your application and use a very simple API in order to summon up the debugger. Let's see how it can be done with a Rails application. I'm going to demonstrate it on my BugTrack application.

  1. Open <bugtrack>/config/environments/development.rb file and append the following line to the end of the file:

    require 'ruby-debug'
    
  2. Open <bugtrack>/app/controllers/user_cotroller.rb file and find login action. What we want is to stop our application at this point and explore what is going on in there:

    def login
      debugger # add this line
      user = User.auth(@params['login'], @params['pwd'])
      if user
        @session[USER_PARAM] = user
        set_filter(user)
      ...
    end
    

    Note that I've added Kernel#debugger method call in the beginning of this method. When the execution gets to this point, we should see our debugger's command prompt.

  3. Now start the application using webrick. Note you can't use lighttpd, because it forks fastcgi processes in the background and they don't have access to the current terminal.

    $ ./script/server webrick
    => Booting WEBrick...
    => Rails application started on http://0.0.0.0:3000
    => Ctrl-C to shutdown server; call with --help for options
    [2006-07-11 12:42:56] INFO  WEBrick 1.3.1
    [2006-07-11 12:42:56] INFO  ruby 1.8.5 (2006-07-11) [i686-darwin8.7.1]
    [2006-07-11 12:42:56] INFO  WEBrick::HTTPServer#start: pid=27917 port=3000
    
  4. Now let's try to login. As soon as I send a login request to the server, on the console I see the debugger prompt:

    ./script/.../controllers/user_controller.rb:59: \
          user = User.auth(@params['login'], @params['pwd'])
    (rdb:2) _
    

    It displays the name of the file .../user_controller.rb where we hit the breakpoint, the line number (59, in that case) and the line of code which will be executed next. At this point you can start playing with the debugger by entering debugger commands and executing them. For the list of all available commands use help command.

Several most-used commands.

Note that most commands have one-two character abbreviations. Again check the output of help command.

  • Show me the code. Use list command to browse code in the current context:

    (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
    

    You can continue browsing by entering more list commands. In order to move in the opposite direction, use - argument. Also you can specify a line number you want to start your listing from or a range of lines separated by a dash character.

  • Evaluate an expression in the current context. Just type any expression you want and the debugger will show you a result of this expression evaluation or an exception:

      (rdb:2) params
      {"action"=>"login", "controller"=>"user", "pwd"=>"letmein", \
       "login"=>"admin"}
    

    You can also use library by using *pp* command.

  • Find where we are at this point. Use where command to see the full stack trace.

    (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'
        ...
    (rdb:2)
    

    The --> arrow indicates the current stack frame selected. It also shows the current evaluation context (see the next command).

  • Move up and down the stack frame. You can use up and down commands in order to change the context to the upper or to the lower frame respectively. Eventually, you can evaluate an expression in the new context. Again, you can use where command to see which frame is currently activate.

    (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
    
  • Stepping the program. Use step command to make a single step, use next command to move to the next line without descending inside methods. Both commands accept an optional numeric argument which specifies how many steps to make:

    (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?
    

    Note that you can move up along the frame stack with *up* command and then use next command to continue execution at the new stack level.

  • Threads listing. Use thread list to display all threads and their statuses. The plus + character and the number indicates the current thread of execution:

    (rdb:2) thread list
     1 #<Thread:0x1f17c4 sleep> /usr/local/lib/ruby/1.8/webrick/server.rb:91
    +2 #<Thread:0x4b3b2b8 run> script/../config/../app/models/user.rb:27
     31 #<Thread:0x4b61238 sleep> /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).

  • Display variables from the current context. Use var local and var global to display local and global variables respectively.

    (rdb:2) var local
      login => "admin"
      pwd => "letmein"
    (rdb:2) var global
      $! => nil
      $" => ["rubygems.rb", "rbconfig.rb", "rubygems/rubygems_version.rb", 
      ...
    
  • Setting breakpoints. Use break [[file:]line] command to add a breakpoint at the given point in the file:

    (rdb:2) b 69
    Set breakpoint 1 at ./script/.../controllers/user_controller.rb:69
    

    or at the method execution:

    (rdb:2) b User.auth
    Set breakpoint 1 at User.auth
    

    Optionally, you can set an expression which defines whether the debugger should stop when it reaches the breakpoint. This expression is evaluated each time at the context of the breakpoint position:

    (rdb:2) b 72 if params['user'] == 'admin'
    Set breakpoint 1 at ./script/.../controllers/user_controller.rb:69
    

    To list all breakpoints use break command without parameters:

    (rdb:2) break
    Breakpoints:
      1 ./script/.../user_controller.rb:69
      2 ./script/.../user_controller.rb:72 if params['user'] == 'admin'
    
  • Continue execution. To continue execution use cont command.

    (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
    

List of all commands

    (rdb:1) help
    ruby-debug help v.0.1.3
    Commands
    b[reak] [file|class:]<line|method> [if expr]
    b[reak] [class.]<line|method> [if expr]
                               set breakpoint to some position,
                               optionally if expr == true
    cat[ch] <an Exception>     set catchpoint to an exception
    cat[ch]                    show catchpoint
    disp[lay] <expression>     add expression into display expression list
    undisp[lay][ nnn]          delete one particular or all display expressions
    b[reak]                    list breakpoints
    del[ete][ nnn]             delete some or all breakpoints
    c[ont]                     run until program ends or hit breakpoint
    r[un]                      alias for cont
    s[tep][ nnn]               step (into methods) one line or till line nnn
    n[ext][ nnn]               go over one line or till line nnn
    w[here]                    display frames
    f[rame]                    alias for where
    l[ist][ (-|nn-mm)]         list program, - list backwards, nn-mm list given lines
    up[ nn]                    move to higher frame
    down[ nn]                  move to lower frame
    fin[ish]                   return to outer frame
    q[uit]                     exit from debugger
    v[ar] g[lobal]             show global variables
    v[ar] l[ocal]              show local variables
    v[ar] i[nstance] <object>  show instance variables of object
    v[ar] c[onst] <object>     show constants of object
    m[ethod] i[nstance] <obj>  show methods of object
    m[ethod] <class|module>    show instance methods of class or module
    th[read] l[ist]            list all threads
    th[read] c[ur[rent]]       show current thread
    th[read] [sw[itch]] <nnn>  switch thread context to nnn
    th[read] stop <nnn>        stop thread nnn
    th[read] resume <nnn>      resume thread nnn
    p expression               evaluate expression and print its value
    pp expression              evaluate expression and print its value
    h[elp]                     print this help
    <everything else>          evaluate

If you find a bug, please file it to the project tracker. Thank you.

Enjoy.

分享到:
评论

相关推荐

    ruby-debug-ide

    除了基本的调试功能,ruby-debug-ide还支持条件断点、监视表达式、远程调试等功能,这些特性可以帮助你更精细地控制调试过程,解决复杂的问题。 总结,ruby-debug-ide是Ruby开发者的得力助手,它使得在IDE中进行...

    ruby-debug-1.87.rar

    1. `ruby-debug-base-0.10.4.gem`:这是`ruby-debug`的核心库,提供了基本的调试功能,如断点管理、堆栈跟踪、变量查看等。它包含了实现调试器所需的大部分逻辑,并为其他模块提供了接口。 2. `linecache19-0.5.12....

    Ruby-Log4r使用Ruby程序一个全面的和灵活的日志库

    要在Ruby项目中使用Log4r,首先需要安装该库。可以通过RubyGems来完成: ```bash gem install log4r ``` **2. 基本用法** Log4r的核心概念包括日志级别、输出器(Outputter)和日志器(Logger)。日志级别通常...

    Ruby-Scrolls简单的日志记录

    Scrolls支持多种日志级别,包括DEBUG、INFO、WARN、ERROR和FATAL,这些级别对应不同的严重程度,可以根据需要调整记录的详细程度。 在使用Scrolls时,首先需要将其添加到你的Gemfile中,然后执行`bundle install`来...

    Ruby-HttpLogHTTP请求日志输出

    首先,我们来了解一下HttpLog的基本用法。在Ruby项目中,你可以通过Gemfile引入HttpLog库,然后在代码中进行初始化。添加以下代码到Gemfile: ```ruby gem 'httplog' ``` 接着运行`bundle install`来安装这个库。...

    lib-ruby-parser:用Rust编写的Ruby解析器

    基本用法: use lib_ruby_parser :: {Parser, ParserOptions, debug_level};fn main () -&gt; Result &lt;(), Box &lt; dyn&gt;&gt; { let options = ParserOptions { buffer_name: "(eval)" . to_string (), debug: debug_...

    phaser-debug-emitter:粒子发射器的调试方法

    如果你的项目是用CoffeeScript编写的,你可以将"phaser-debug-emitter"集成到代码中,方法与JavaScript基本一致,只是语法有所不同。 为了更好地利用"phaser-debug-emitter",你需要熟悉Phaser的粒子发射器API。...

    Ruby语言笔记包括简介、主要特性、命令行选项、环境变量、基础语法等

    ### Ruby语言概述 #### 一、Ruby语言简介 Ruby是一种纯粹的面向对象的编程...通过了解Ruby的基本概念、主要特性和如何通过命令行进行配置,开发者可以更好地利用这种语言的强大功能,构建高效、可维护的应用程序。

    Ruby经典学习教程(口碑不错)

    ### Ruby经典学习教程知识点梳理 #### 一、Ruby语言概述 **1.1 Ruby的历史** - **起源**:Ruby语言最初由日本人松本行弘(Yukihiro Matsumoto)于1995年...- 可以使用`debug`或`tracer`等工具来监控程序的执行过程。

    qiitan-debug-beginner:Qiita复制应用程序的调试测试(级别1)

    大部分内容是基本的。 错误-&gt;屏幕未出现 错误-&gt;行为异常 中间版本 目标人 阅读不止一本Rails书籍或完成Rails教程 没有Rails工作经验 调试程序 根据环境建设程序建设环境 复制答案模板表 将分支更改为debug-test 开始...

    ruby logger

    在Ruby编程语言中,`...总的来说,Ruby的`logger`模块提供了一套完整的日志解决方案,它易于使用且可定制化程度高,适合各种规模的项目。通过理解和充分利用这些特性,开发者可以更好地监控和调试他们的应用程序。

    rb101:Ruby赛道101

    2. 编写第一个Ruby程序:介绍`puts`、`print`等基本输出函数,以及变量的使用。 3. 控制流程:学习if语句、case语句、循环(while、for、each)等控制结构。 4. 函数和方法:理解函数和方法的区别,学习如何定义和...

    Ruby的语法类似于英语,易于阅读和理解 它支持多种编程范式,包括面向对象编程、过程式编程和函数式编程

    ### Ruby编程语言概述 #### 一、Ruby简介 Ruby是一种高级、通用的编程语言,以其简单易学、灵活多变的语法而闻名。...无论是使用Ruby还是其他语言,理解和掌握RESTful API的设计原则对于开发者来说都是非常重要的。

    JavaEye3.0开发手记

    通过安装`ruby-debug`或类似的调试工具,可以在开发过程中进行单步调试、设置断点等功能,从而更加高效地定位和解决问题。 综上所述,为了搭建一个高效且功能完善的开发环境,需要综合考虑IDE的选择、命令行工具的...

    kchung:招聘在这里查看我的工作! 随着时间的推移收集的项目和迷你作业

    旧的迷你项目 ... BST-Debug - 在 C 中使用调试实用程序 GradeList - 解析带有成绩的文件以排序和查找基本数学 直方图 - 计算字母的出现次数并显示可视直方图 ListSort - 使用指针,对链表的节点进行排序 先进

    serinette:从命令行生成随机电子音乐

    安装 gem install serinette基本用法我们还没有到那里,但它会像这样工作: serinette orchestrate或者,您可以向 serinette 传递一系列令人惊叹的标志和参数以及其他内容(您还不能) serinette orchestrate --wow ...

    sencha cmd 使用方法

    - 使用 `sencha build` 命令来构建应用,可以选择不同的构建类型如 `debug` 或 `production`。 - 构建后会在指定目录下生成打包好的文件。 8. **调试与测试**: - 在开发过程中可以使用 `sencha app watch` 命令...

    用Ruby实现一个单元测试框架的教程

    这篇教程将向你展示如何使用Ruby实现一个基础的单元测试框架,这对于理解测试驱动开发(TDD)的理念以及调试Ruby代码中的错误(即Ruby debug)非常有帮助。我们将通过以下几个步骤构建一个简单的测试框架: 1. **...

    数据缓存--Memcach详解及如何使用(带代码)?

    **一、Memcached的基本概念** 1. **键值对存储**:Memcached采用键值对(key-value)存储方式,键是唯一的标识符,值是存储的数据。 2. **内存管理**:内存被划分为大小固定的 slab 分区,每个分区管理一部分键值对,...

    Eagle旅游网的设计与实现-计算机应用专业.pdf

    * 后端技术:使用Java、Python、Ruby等技术,实现业务逻辑的开发。 * 数据库技术:使用MySQL、Oracle、SQL Server等技术,实现数据的存储和管理。 ### 代码规范原则 Eagle旅游网的代码规范原则主要基于以下几个...

Global site tag (gtag.js) - Google Analytics