<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Debugging Rails Applications</title>
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
<![endif]-->
<link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
<link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
<link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
<style type="text/css">
div#container {
max-width: 900px;
padding-bottom: 3em;
}
div#content {
margin-left: 200px;
}
div#container.notoc {
max-width: 600px;
}
.notoc div#content {
margin-left: 0;
}
pre {
line-height: 1.4em;
}
#content p tt {
background: #eeeeee;
border: solid 1px #cccccc;
padding: 3px;
}
dt {
font-weight: bold;
}
#content dt tt {
font-size: 10pt;
}
dd {
margin-left: 3em;
}
#content dt tt, #content pre tt {
background: none;
padding: 0;
border: 0;
}
#content .olist ol {
margin-left: 2em;
}
#header {
position: relative;
max-width: 840px;
margin-left: auto;
margin-right: auto;
}
#header.notoc {
max-width: 580px;
}
#logo {
position: absolute;
left: 10px;
top: 10px;
width: 110px;
height: 140px;
}
div#header h1#site_title {
background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
position: absolute;
width: 392px;
height: 55px;
left: 145px;
top: 20px;
margin: 0;
padding: 0;
}
#site_title span {
display: none;
}
#site_title_tagline {
display: none;
}
ul#navMain {
position: absolute;
margin: 0;
padding: 0;
top: 97px;
left: 145px;
}
.left-floaty, .right-floaty {
padding: 15px;
}
.admonitionblock,
.tableblock {
margin-left: 1em;
margin-right: 1em;
margin-top: 0.25em;
margin-bottom: 1em;
}
.admonitionblock .icon {
padding-right: 8px;
}
.admonitionblock .content {
border: solid 1px #ffda78;
background: #fffebd;
padding: 10px;
padding-top: 8px;
padding-bottom: 8px;
}
.admonitionblock .title {
font-size: 140%;
margin-bottom: 0.5em;
}
.tableblock table {
border: solid 1px #aaaaff;
background: #f0f0ff;
}
.tableblock th {
background: #e0e0e0;
}
.tableblock th,
.tableblock td {
padding: 3px;
padding-left: 5px;
padding-right: 5px;
}
.sidebarblock {
margin-top: 0.25em;
margin: 1em;
border: solid 1px #ccccbb;
padding: 8px;
background: #ffffe0;
}
.sidebarblock .sidebar-title {
font-size: 140%;
font-weight: 600;
margin-bottom: 0.3em;
}
.sidebarblock .sidebar-content > .para:last-child > p {
margin-bottom: 0;
}
.sidebarblock .sidebar-title a {
text-decoration: none;
}
.sidebarblock .sidebar-title a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div id="header" >
<div id="logo">
<a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
</div>
<h1 id="site_title"><span>Ruby on Rails</span></h1>
<h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
<ul id="navMain">
<li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
<li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
</ul>
</div>
<div id="container">
<div id="sidebar">
<h2>Chapters</h2>
<ol>
<li>
<a href="#_view_helpers_for_debugging">View Helpers for Debugging</a>
<ul>
<li><a href="#_debug">debug</a></li>
<li><a href="#_to_yaml">to_yaml</a></li>
<li><a href="#_inspect">inspect</a></li>
</ul>
</li>
<li>
<a href="#_the_logger">The Logger</a>
<ul>
<li><a href="#_what_is_the_logger">What is The Logger?</a></li>
<li><a href="#_log_levels">Log Levels</a></li>
<li><a href="#_sending_messages">Sending Messages</a></li>
</ul>
</li>
<li>
<a href="#_debugging_with_ruby_debug">Debugging with ruby-debug</a>
<ul>
<li><a href="#_setup">Setup</a></li>
<li><a href="#_the_shell">The Shell</a></li>
<li><a href="#_the_context">The Context</a></li>
<li><a href="#_threads">Threads</a></li>
<li><a href="#_inspecting_variables">Inspecting Variables</a></li>
<li><a href="#_step_by_step">Step by Step</a></li>
<li><a href="#_breakpoints">Breakpoints</a></li>
<li><a href="#_catching_exceptions">Catching Exceptions</a></li>
<li><a href="#_resuming_execution">Resuming Execution</a></li>
<li><a href="#_editing">Editing</a></li>
<li><a href="#_quitting">Quitting</a></li>
<li><a href="#_settings">Settings</a></li>
</ul>
</li>
<li>
<a href="#_references">References</a>
</li>
<li>
<a href="#_changelog">Changelog</a>
</li>
</ol>
</div>
<div id="content">
<h1>Debugging Rails Applications</h1>
<div id="preamble">
<div class="sectionbody">
<div class="para"><p>This guide introduces techniques for debugging Ruby on Rails applications. By referring to this guide, you will be able to:</p></div>
<div class="ilist"><ul>
<li>
<p>
Understand the purpose of debugging
</p>
</li>
<li>
<p>
Track down problems and issues in your application that your tests aren't identifying
</p>
</li>
<li>
<p>
Learn the different ways of debugging
</p>
</li>
<li>
<p>
Analyze the stack trace
</p>
</li>
</ul></div>
</div>
</div>
<h2 id="_view_helpers_for_debugging">1. View Helpers for Debugging</h2>
<div class="sectionbody">
<div class="para"><p>One common task is to inspect the contents of a variable. In Rails, you can do this with three methods:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>debug</tt>
</p>
</li>
<li>
<p>
<tt>to_yaml</tt>
</p>
</li>
<li>
<p>
<tt>inspect</tt>
</p>
</li>
</ul></div>
<h3 id="_debug">1.1. debug</h3>
<div class="para"><p>The <tt>debug</tt> helper will return a <pre>-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><%= debug @post %>
<span style="font-weight: bold"><span style="color: #0000FF"><p></span></span>
<span style="font-weight: bold"><span style="color: #0000FF"><b></span></span>Title:<span style="font-weight: bold"><span style="color: #0000FF"></b></span></span>
<%=h @post.title %>
<span style="font-weight: bold"><span style="color: #0000FF"></p></span></span>
</tt></pre></div></div>
<div class="para"><p>You'll see something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>--- !ruby/object:Post
attributes:
updated_at: 2008-09-05 22:55:47
body: It's a very helpful guide for debugging your Rails app.
title: Rails debugging guide
published: t
id: "1"
created_at: 2008-09-05 22:55:47
attributes_cache: {}
Title: Rails debugging guide
</tt></pre></div></div>
<h3 id="_to_yaml">1.2. to_yaml</h3>
<div class="para"><p>Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><%= simple_format @post.to_yaml %>
<span style="font-weight: bold"><span style="color: #0000FF"><p></span></span>
<span style="font-weight: bold"><span style="color: #0000FF"><b></span></span>Title:<span style="font-weight: bold"><span style="color: #0000FF"></b></span></span>
<%=h @post.title %>
<span style="font-weight: bold"><span style="color: #0000FF"></p></span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>to_yaml</tt> method converts the method to YAML format leaving it more readable, and then the <tt>simple_format</tt> helper is used to render each line as in the console. This is how <tt>debug</tt> method does its magic.</p></div>
<div class="para"><p>As a result of this, you will have something like this in your view:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>--- !ruby/object:Post
attributes:
updated_at: 2008-09-05 22:55:47
body: It's a very helpful guide for debugging your Rails app.
title: Rails debugging guide
published: t
id: "1"
created_at: 2008-09-05 22:55:47
attributes_cache: {}
Title: Rails debugging guide
</tt></pre></div></div>
<h3 id="_inspect">1.3. inspect</h3>
<div class="para"><p>Another useful method for displaying object values is <tt>inspect</tt>, especially when working with arrays or hashes. This will print the object value as a string. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><%= [1, 2, 3, 4, 5].inspect %>
<span style="font-weight: bold"><span style="color: #0000FF"><p></span></span>
<span style="font-weight: bold"><span style="color: #0000FF"><b></span></span>Title:<span style="font-weight: bold"><span style="color: #0000FF"></b></span></span>
<%=h @post.title %>
<span style="font-weight: bold"><span style="color: #0000FF"></p></span></span>
</tt></pre></div></div>
<div class="para"><p>Will be rendered as follows:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>[1, 2, 3, 4, 5]
Title: Rails debugging guide
</tt></pre></div></div>
</div>
<h2 id="_the_logger">2. The Logger</h2>
<div class="sectionbody">
<div class="para"><p>It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.</p></div>
<h3 id="_what_is_the_logger">2.1. What is The Logger?</h3>
<div class="para"><p>Rails makes use of Ruby's standard <tt>logger</tt> to write log information. You can also substitute another logger such as <tt>Log4R</tt> if you wish.</p></div>
<div class="para"><p>You can specify an alternative logger in your <tt>environment.rb</tt> or any environment file:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span>STDOUT<span style="color: #990000">)</span>
ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Log4r<span style="color: #990000">::</span>Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"Application Log"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>Or in the <tt>Initializer</tt> section, add <em>any</em> of the following</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>config<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span>STDOUT<span style="color: #990000">)</span>
config<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Log4r<span style="color: #990000">::</span>Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"Application Log"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">By default, each log is created under <tt>RAILS_ROOT/log/</tt> and the log file name is <tt>environment_name.log</tt>.</td>
</tr></table>
</div>
<h3 id="_log_levels">2.2. Log Levels</h3>
<div class="para"><p>When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the <tt>ActiveRecord::Base.logger.level</tt> method.</p></div>
<div class="para"><p>The available log levels are: <tt>:debug</tt>, <tt>:info</tt>, <tt>:warn</tt>, <tt>:error</tt>, and <tt>:fatal</tt>, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>config<span style="color: #990000">.</span>log_level <span style="color: #990000">=</span> Logger<span style="color: #990000">::</span>WARN <span style="font-style: italic"><span style="color: #9A1900"># In any environment initializer, or</span></span>
ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger<span style="color: #990000">.</span>level <span style="color: #990000">=</span> <span style="color: #993399">0</span> <span style="font-style: italic"><span style="color: #9A1900"># at any time</span></span>
</tt></pre></div></div>
<div class="para"><p>This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">The default Rails log level is <tt>info</tt> in production mode and <tt>debug</tt> in development and test mode.</td>
</tr></table>
</div>
<h3 id="_sending_messages">2.3. Sending Messages</h3>
<div class="para"><p>To write in the current log use the <tt>logger.(debug|info|warn|error|fatal)</tt> method from within a controller, model or mailer:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>logger<span style="color: #990000">.</span>debug <span style="color: #FF0000">"Person attributes hash: #{@person.attributes.inspect}"</span>
logger<span style="color: #990000">.</span>info <span style="color: #FF0000">"Processing the request..."</span>
logger<span style="color: #990000">.</span>fatal <span style="color: #FF0000">"Terminating application, raised unrecoverable error!!!"</span>
</tt></pre></div></div>
<div class="para"><p>Here's an example of a method instrumented with extra logging:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsController <span style="color: #990000"><</span> ApplicationController
<span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> create
<span style="color: #009900">@post</span> <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>post<span style="color: #990000">])</span>
logger<span style="color: #990000">.</span>debug <span style="color: #FF0000">"New post: #{@post.attributes.inspect}"</span>
logger<span style="color: #990000">.</span>debug <span style="color: #FF0000">"Post should be valid: #{@post.valid?}"</span>
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>save
flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">'Post was successfully created.'</span>
logger<span style="color: #990000">.</span>debug <span style="color: #FF0000">"The post was saved and now is the user is going to be redirected..."</span>
redirect_to<span style="color: #990000">(</span><span style="color: #009900">@post</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
render <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"new"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Here's an example of the log generated by this method:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>Processing PostsController#create (for <span style="color: #009900">127.0.0.1</span> at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
"body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
"authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
"published"=>false, "created_at"=>nil}
Post should be valid: true
Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
"created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
The post was saved and now is the user is going to be redirected...
Redirected to #<Post:0x20af760>
Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
</tt></pre></div></div>
<div class="para"><p>Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia.</p></div>
</div>
<h2 id="_debugging_with_ruby_debug">3. Debugging with ruby-debug</h2>
<div class="sectionbody">
<div class="para"><p>When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.</p></div>
<div class="para"><p>The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code.</p></div>
<h3 id="_setup">3.1. Setup</h3>
<div class="para"><p>The debugger used by Rails, <tt>ruby-debug</tt>, comes as a gem. To install it, just run:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>$ sudo gem install ruby-debug
</tt></pre></div></div>
<div class="para"><p>In case you want to download a particular version or get the source code, refer to the <a href="http://rubyforge.org/projects/ruby-debug/">project's page on rubyforge</a>.</p></div>
<div class="para"><p>Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the <tt>debugger</tt> method.</p></div>
<div class="para"><p>Here's an example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PeopleController <span style="color: #990000"><</span> ApplicationController
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
debugger
<span style="color: #009900">@person</span> <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you see the message in the console or logs:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>***** Debugger requested, but was not available: Start server with --debugger to enable *****
</tt></pre></div></div>
<div class="para"><p>Make sure you have started your web server with the option <tt>—debugger</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #990000">~</span>/PathTo/rails_project$ script/server --debugger
<span style="color: #990000">=></span> Booting Mongrel <span style="color: #990000">(</span>use <span style="color: #FF0000">'script/server webrick'</span> to force WEBrick<span style="color: #990000">)</span>
<span style="color: #990000">=></span> Rails <span style="color: #993399">2.2</span><span style="color: #990000">.</span><span style="color: #993399">0</span> application starting on http<span style="color: #990000">://</span><span style="color: #993399">0.0</span><span style="color: #990000">.</span><span style="color: #993399">0.0</span><span style="color: #990000">:</span><span style="color: #993399">3000</span>
<span style="color: #990000">=></span> Debugger enabled
<span style="color: #990000">...</span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">In development mode, you can dynamically <tt>require 'ruby-debug'</tt> instead of restarting the server, if it was started without <tt>—debugger</tt>.</td>
</tr></table>
</div>
<div class="para"><p>In order to use Rails debugging you'll need to be running either <strong>WEBrick</strong> or <strong>Mongrel</strong>. For the moment, no alternative servers are supported.</p></div>
<h3 id="_the_shell">3.2. The Shell</h3>
<div class="para"><p>As soon as your application calls the <tt>debugger</tt> method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt <tt>(rdb:n)</tt>. The <em>n</em> is the thread number. The prompt will also show you the next line of code that is waiting to run.</p></div>
<div class="para"><p>If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request.</p></div>
<div class="para"><p>For example:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>@posts = Post.find(:all)
(rdb:7)</tt></pre>
</div></div>
<div class="para"><p>Now it's time to play and dig into your application. A good place to start is by asking the debugger for help… so type: <tt>help</tt> (You didn't see that coming, right?)</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:7) help
ruby-debug help v0.10.2
Type 'help <command-name>' for help on a specific command
Available commands:
backtrace delete enable help next quit show trace
break disable eval info p reload source undisplay
catch display exit irb pp restart step up
condition down finish list ps save thread var
continue edit frame method putl set tmate where</tt></pre>
</div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">To view the help menu for any command use <tt>help <command-name></tt> in active debug mode. For example: <em><tt>help var</tt></em></td>
</tr></table>
</div>
<div class="para"><p>The next command to learn is one of the most useful: <tt>list</tt>. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use <tt>l</tt> for the <tt>list</tt> command.</p></div>
<div class="para"><p>This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by <tt>⇒</tt>.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:7) list
[1, 10] in /PathToProject/posts_controller.rb
1 class PostsController < ApplicationController
2 # GET /posts
3 # GET /posts.xml
4 def index
5 debugger
=> 6 @posts = Post.find(:all)
7
8 respond_to do |format|
9 format.html # index.html.erb
10 format.xml { render :xml => @posts }</tt></pre>
</div></div>
<div class="para"><p>If you repeat the <tt>list</tt> command, this time using just <tt>l</tt>, the next ten lines of the file will be printed out.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:7) l
[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
11 end
12 end
13
14 # GET /posts/1
15 # GET /posts/1.xml
16 def show
17 @post = Post.find(params[:id])
18
19 respond_to do |format|
20 format.html # show.html.erb</tt></pre>
</div></div>
<div class="para"><p>And so on until the end of the current file. When the end of file is reached, the <tt>list</tt> command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer.</p></div>
<h3 id="_the_context">3.3. The Context</h3>
<div class="para"><p>When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack.</p></div>
<div class="para"><p>ruby-debug creates a content when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped.</p></div>
<div class="para"><p>At any time you can call the <tt>backtrace</tt> command (or its alias <tt>where</tt>) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then <tt>backtrace</tt> will supply the answer.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:5) where
#0 PostsController.index
at line /PathTo/project/app/controllers/posts_controller.rb:6
#1 Kernel.send
at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
#2 ActionController::Base.perform_action_without_filters
at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
#3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617
...</tt></pre>
</div></div>
<div class="para"><p>You move anywhere you want in this trace (thus changing the context) by using the <tt>frame <em>n</em></tt> command, where <em>n</em> is the specified frame number.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:5) frame 2
#2 ActionController::Base.perform_action_without_filters
at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175</tt></pre>
</div></div>
<div class="para"><p>The available variables are the same as if you were running the code line by line. After all, that's what debugging is.</p></div>
<div class="para"><p>Moving up and down the stack frame: You can use <tt>up [n]</tt> (<tt>u</tt> for abbreviated) and <tt>down [n]</tt> commands in order to change the context <em>n</em> frames up or down the stack respectively. <em>n</em> defaults to one. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames.</p></div>
<h3 id="_threads">3.4. Threads</h3>
<div class="para"><p>The debugger can list, stop, resume and switch between running threads by using the command <tt>thread</tt> (or the abbreviated <tt>th</tt>). This command has a handful of options:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>thread</tt> shows the current thread.
</p>
</li>
<li>
<p>
<tt>thread list</tt> is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution.
</p>
</li>
<li>
<p>
<tt>thread stop <em>n</em></tt> stop thread <em>n</em>.
</p>
</li>
<li>
<p>
<tt>thread resume <em>n</em></tt> resumes thread <em>n</em>.
</p>
</li>
<li>
<p>
<tt>thread switch <em>n</em></tt> switches the current thread context to <em>n</em>.
</p>
</li>
</ul></div>
<div class="para"><p>This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code.</p></div>
<h3 id="_inspecting_variables">3.5. Inspecting Variables</h3>
<div class="para"><p>Any expression can be evaluated in the current context. To evaluate an expression, just type it!</p></div>
<div class="para"><p>This example shows how you can print the instance_variables defined within the current context:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>@posts = Post.find(:all)
(rdb:11) instance_variables
["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]</tt></pre>
</div></div>
<div class="para"><p>As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using <tt>next</tt> (you'll learn more about this command later in this guide).</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:11) next
Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
Parameters: {"action"=>"index", "controller"=>"posts"}
/PathToProject/posts_controller.rb:8
respond_to do |format|</tt></pre>
</div></div>
<div class="para"><p>And then ask again for the instance_variables:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:11) instance_variables.include? "@posts"
true</tt></pre>
</div></div>
<div class="para"><p>Now <tt>@posts</tt> is a included in the instance variables, because the line defining it was executed.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">You can also step into <strong>irb</strong> mode with the command <tt>irb</tt> (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature.</td>
</tr></table>
</div>
<div class="para"><p>The <tt>var</tt> method is the most convenient way to show variables and their values:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>var
(rdb:1) v[ar] const <object> show constants of object
(rdb:1) v[ar] g[lobal] show global variables
(rdb:1) v[ar] i[nstance] <object> show instance variables of object
(rdb:1) v[ar] l[ocal] show local variables</tt></pre>
</div></div>
<div class="para"><p>This is a great way to inspect the values of the current context variables. For example:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:9) var local
__dbg_verbose_save => false</tt></pre>
</div></div>
<div class="para"><p>You can also inspect for an object method this way:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:9) var instance Post.new
@attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"...
@attributes_cache = {}
@new_record = true</tt></pre>
</div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">The commands <tt>p</tt> (print) and <tt>pp</tt> (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console.</td>
</tr></table>
</div>
<div class="para"><p>You can use also <tt>display</tt> to start watching variables. This is a good way of tracking the values of a variable while the execution goes on.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:1) display @recent_comments
1: @recent_comments =</tt></pre>
</div></div>
<div class="para"><p>The variables inside the displaying list will be printed with their values after you move in the stack. To stop displaying a variable use <tt>undisplay <em>n</em></tt> where <em>n</em> is the variable number (1 in the last example).</p></div>
<h3 id="_step_by_step">3.6. Step by Step</h3>
<div class="para"><p>Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution.</p></div>
<div class="para"><p>Use <tt>step</tt> (abbreviated <tt>s</tt>) to continue running your program until the next logical stopping point and return control to ruby-debug.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">You can also use <tt>step+ <em>n</em></tt> and <tt>step- <em>n</em></tt> to move forward or backward <em>n</em> steps respectively.</td>
</tr></table>
</div>
<div class="para"><p>You may also use <tt>next</tt> which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move <em>n</em> steps.</p></div>
<div class="para"><p>The difference between <tt>next</tt> and <tt>step</tt> is that <tt>step</tt> stops at the next line of code executed, doing just a single step, while <tt>next</tt> moves to the next line without descending inside methods.</p></div>
<div class="para"><p>For example, consider this block of code with an included <tt>debugger</tt> statement:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Author <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
has_one <span style="color: #990000">:</span>editorial
has_many <span style="color: #990000">:</span>comments
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> find_recent_comments<span style="color: #990000">(</span>limit <span style="color: #990000">=</span> <span style="color: #993399">10</span><span style="color: #990000">)</span>
debugger
<span style="color: #009900">@recent_comments</span> <span style="color: #990000">||=</span> comments<span style="color: #990000">.</span>find<span style="color: #990000">(</span>
<span style="color: #990000">:</span>all<span style="color: #990000">,</span>
<span style="color: #990000">:</span>conditions <span style="color: #990000">=></span> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at > ?"</span><span style="color: #990000">,</span> <span style="color: #993399">1</span><span style="color: #990000">.</span>week<span style="color: #990000">.</span>ago<span style="color: #990000">],</span>
<span style="color: #990000">:</span>limit <span style="color: #990000">=></span> limit
<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">You can use ruby-debug while using script/console. Just remember to <tt>require "ruby-debug"</tt> before calling the <tt>debugger</tt> method.</td>
</tr></table>
</div>
<div class="listingblock">
<div class="content">
<pre><tt>/PathTo/project $ script/console
Loading development environment (Rails 2.1.0)
>> require "ruby-debug"
=> []
>> author = Author.first
=> #<Author id: 1, first_name: "Bob", last_name: "Smith", created_at: "2008-07-31 12:46:10", updated_at: "2008-07-31 12:46:10">
>> author.find_recent_comments
/PathTo/project/app/models/author.rb:11
)</tt></pre>
</div></div>
<div class="para"><p>With the code stopped, take a look around:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:1) list
[6, 15] in /PathTo/project/app/models/author.rb
6 debugger
7 @recent_comments ||= comments.find(
8 :all,
9 :conditions => ["created_at > ?", 1.week.ago],
10 :limit => limit
=> 11 )
12 end
13 end</tt></pre>
</div></div>
<div class="para"><p>You are at the end of the line, but… was this line executed? You can inspect the instance variables.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:1) var instance
@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
@attributes_cache = {}</tt></pre>
</div></div>
<div class="para"><p><tt>@recent_comments</tt> hasn't been defined yet, so it's clear that this line hasn't been executed yet. Use the <tt>next</tt> command to move on in the code:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:1) next
/PathTo/project/app/models/author.rb:12
@recent_comments
(rdb:1) var instance
@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
@attributes_cache = {}
@comments = []
@recent_comments = []</tt></pre>
</div></div>
<div class="para"><p>Now you can see that the <tt>@comments</tt> relationship was loaded and @recent_comments defined because the line was executed.</p></div>
<div class="para"><p>If you want to go deeper into the stack trace you can move single <tt>steps</tt>, through your calling methods and into Rails code. This is one of the best ways to find bugs in your code, or perhaps in Ruby or Rails.</p></div>
<h3 id="_breakpoints">3.7. Breakpoints</h3>
<div class="para"><p>A breakpoint makes your application stop whenever a certain point in the program is reached. The debugger shell is invoked in that line.</p></div>
<div class="para"><p>You can add breakpoints dynamically with the command <tt>break</tt> (or just <tt>b</tt>). There are 3 possible ways of adding breakpoints manually:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>break line</tt>: set breakpoint in the <em>line</em> in the current source file.
</p>
</li>
<li>
<p>
<tt>break file:line [if expression]</tt>: set breakpoint in the <em>line</em> number inside the <em>file</em>. If an <em>expression</em> is given it must evaluated to <em>true</em> to fire up the debugger.
</p>
</li>
<li>
<p>
<tt>break class(.|#)method [if expression]</tt>: set breakpoint in <em>method</em> (. and # for class and instance method respectively) defined in <em>class</em>. The <em>expression</em> works the same way as with file:line.
</p>
</li>
</ul></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:5) break 10
Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10</tt></pre>
</div></div>
<div class="para"><p>Use <tt>info breakpoints <em>n</em></tt> or <tt>info break <em>n</em></tt> to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:5) info breakpoints
Num Enb What
1 y at filters.rb:10</tt></pre>
</div></div>
<div class="para"><p>To delete breakpoints: use the command <tt>delete <em>n</em></tt> to remove the breakpoint number <em>n</em>. If no number is specified, it deletes all breakpoints that are currently active..</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:5) delete 1
(rdb:5) info breakpoints
No breakpoints.</tt></pre>
</div></div>
<div class="para"><p>You can also enable or disable breakpoints:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>enable breakpoints</tt>: allow a list <em>breakpoints</em> or all of them if no list is specified, to stop your program. This is the default state when you create a breakpoint.
</p>
</li>
<li>
<p>
<tt>disable breakpoints</tt>: the <em>breakpoints</em> will have no effect on your program.
</p>
</li>
</ul></div>
<h3 id="_catching_exceptions">3.8. Catching Exceptions</h3>
<div class="para"><p>The command <tt>catch exception-name</tt> (or just <tt>cat exception-name</tt>) can be used to intercept an exception of type <em>exception-name</em> when there would otherwise be is no handler for it.</p></div>
<div class="para"><p>To list all active catchpoints use <tt>catch</tt>.</p></div>
<h3 id="_resuming_execution">3.9. Resuming Execution</h3>
<div class="para"><p>There are two ways to resume execution of an application that is stopped in the debugger:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>continue</tt> [line-specification] (or <tt>c</tt>): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
</p>
</li>
<li>
<p>
<tt>finish</tt> [frame-number] (or <tt>fin</tt>): execute until the selected stack frame returns. If no frame number is given, the application 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 it will run until the specified frame returns.
</p>
</li>
</ul></div>
<h3 id="_editing">3.10. Editing</h3>
<div class="para"><p>Two commands allow you to open code from the debugger into an editor:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>edit [file:line]</tt>: edit <em>file</em> using the editor specified by the EDITOR environment variable. A specific <em>line</em> can also be given.
</p>
</li>
<li>
<p>
<tt>tmate <em>n</em></tt> (abbreviated <tt>tm</tt>): open the current file in TextMate. It uses n-th frame if <em>n</em> is specified.
</p>
</li>
</ul></div>
<h3 id="_quitting">3.11. Quitting</h3>
<div class="para"><p>To exit the debugger, use the <tt>quit</tt> command (abbreviated <tt>q</tt>), or its alias <tt>exit</tt>.</p></div>
<div class="para"><p>A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again.</p></div>
<h3 id="_settings">3.12. Settings</h3>
<div class="para"><p>There are some settings that can be configured in ruby-debug to make it easier to debug your code. Here are a few of the available options:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>set reload</tt>: Reload source code when changed.
</p>
</li>
<li>
<p>
<tt>set autolist</tt>: Execute <tt>list</tt> command on every breakpoint.
</p>
</li>
<li>
<p>
<tt>set listsize <em>n</em></tt>: Set number of source lines to list by default to <em>n</em>.
</p>
</li>
<li>
<p>
<tt>set forcestep</tt>: Make sure the <tt>next</tt> and <tt>step</tt> commands always move to a new line
</p>
</li>
</ul></div>
<div class="para"><p>You can see the full list by using <tt>help set</tt>. Use <tt>help set <em>subcommand</em></tt> to learn about a particular <tt>set</tt> command.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="/Users/lifo/Docs/docrails/railties/doc/guides/source/icons/tip.png" alt="Tip" />
</td>
<td class="content">You can include any number of these configuration lines inside a <tt>.rdebugrc</tt> file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly.</td>
</tr></table>
</div>
<div class="para"><p>Here's a good start for an <tt>.rdebugrc</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>set autolist
set forcestep
set listsize 25
</tt></pre></div></div>
</div>
<h2 id="_references">4. References</h2>
<div class="sectionbody">
<div class="ilist"><ul>
<li>
<p>
<a href="http://www.datanoise.com/ruby-debug">ruby-debug Homepage</a>
</p>
</li>
<li>
<p>
<a href="http://www.sitepoint.com/article/debug-rails-app-ruby-debug/">Article: Debugging a Rails application with ruby-debug</a>
</p>
</li>
<li>
<p>
<a href="http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/">ruby-debug Basics screencast</a>
</p>
</li>
<li>
<p>
<a href="http://railscasts.com/episodes/54-debugging-with-ruby-debug">Ryan Bate's ruby-debug screencast</a>
</p>
</li>
<li>
<p>
<a href="http://railscasts.com/episodes/24-the-stack-trace">Ryan Bate's stack trace screencast</a>
</p>
</li>
<li>
<p>
<a href="http://railscasts.com/episodes/56-the-logger">Ryan Bate's logger screencast</a>
</p>
</li>
<li>
<p>
<a href="http://bashdb.sourceforge.net/ruby-debug.html">Debugging with ruby-debug</a>
</p>
</li>
<li>
<p>
<a href="http://cheat.errtheblog.com/s/rdebug/">ruby-debug cheat sheet</a>
</p>
</li>
<li>
<p>
<a href="http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging">Ruby on Rails Wiki: How to Configure Logging</a>
</p>
</li>
</ul></div>
</div>
<h2 id="_changelog">5. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
October 19, 2008: Copy editing pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
<li>
<p>
September 16, 2008: initial version by <a href="../authors.html#miloops">Emilio Tagua</a>
</p>
</li>
</ul></div>
</div>
</div>
</div>
</body>
</html>