RSS-feed

Mon, 10 Nov 2008

Error Tracing in ruby


Have you ever wonder how Rails and other ruby based frameworks include backtrace information whenever there is an exception? Me too. It is very well explained in the TRPL (The Ruby Programming Language). Check out this code:

SCRIPT_LINES__ = {__FILE__ => File.readlines(__FILE__)}

class Foo
  def lala
    code = []
    (0..3).each { |i| code << SCRIPT_LINES__[__FILE__][__LINE__-(4-i)] }
    raise ArgumentError,
          "\n Problems here:\n #{"_" * 40}\n #{code} #{"_" * 40}\n ",
          caller
  end

  def foo
    lala
  end
end

Foo.new.foo

If you run it (1.8.7), you'll get something like:

./foo.rb:14:in `foo':  (ArgumentError) Problems here:
 ________________________________________
 class Foo
  def lala
    code = []
    (0..3).each { |i| code << SCRIPT_LINES__[__FILE__][__LINE__-(4-i)] }
 ________________________________________
 
        from ./foo.rb:18

That is quite similar to the output you get in one of those frameworks we were mentioning before. Yes, already, not as nicer. The secret is that SCRIPT_LINES__ constant. There we hash our code file and then we use when necessary. Here while raising an exception.

posted at: 13:47 | path: /ruby | permanent link to this entry