Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

52 | Chapter 2: ActiveSupport and RailTies


[[:unknown, :unknown, "./call_stack1.8.5.rb", 18, nil, nil],
[Test, :foo, "./call_stack1.8.5.rb", 9, #<Binding:0x13c8ba0>, :Ruby],
[Test, :bar, "./call_stack1.8.5.rb", 13, #<Binding:0x13c8b78>, :Ruby]]
baz

The first line of that backtrace corresponds to thecall_stack_onmethod. A warn-
ing: sincecall_stackworks by hooking every method call and return, it slows execu-
tion even when the data collected is not being used.


We can usecall_stackto our advantage to trace the flow of execution through a
Rails request. After installing thecall_stackgem, place these two lines at the end of
environment.rb:


require 'call_stack'
call_stack_on

Then, you can place the following line in an action to log a stack trace with the class
name and function name for each stack frame:


logger.info(call_stack(-1).map{|frame| "#{frame[0]} : #{frame[1]}"} * "\n")

Debugging Ruby and Rails


Ruby ships with a built-in debugger, rdebug. However, Kent Sibilev has improved
upon this and released his own Ruby debugging library,ruby-debug. This is a full-
featured Ruby debugger that also includes breakpoint support for Rails.


Rails used to have built-in debugging support, based onBinding.of_
caller, that exploited a Ruby 1.8.4 bug. When the bug was fixed in
Ruby 1.8.5, the breakpointer broke and we had to rely on third-party
utilities to debug Rails applications.

To start using ruby-debug, install it withgem:


$ sudo gem install ruby-debug

When installed, ruby-debug installs anrdebugbinary that is called just like the Ruby
executable. To debug simple Ruby scripts, just run your scripts withrdebugrather
thanruby. This is an extremely helpful way to examine the path Ruby takes to exe-
cute a script.


We can see an example of this with a simple time-reporting script based on Ruby
Reports:http://rubyreports.org/. This script reads a CSV file and generates a simple
PDF based on it:


time_report.rb


#!/usr/local/bin/ruby

require "rubygems"
require "ruport"
Free download pdf