Really useful Rails/Ruby debug helper functions

OK, so printing stuff out to the console is pretty important when debugging your really nifty RoR application. Here’s a couple that we find exceptionally useful:

Defines a new method ‘pm’ on the Kernel object which prints out a readable, sorted list of the methods on the specified object

Kernel.send(:define_method, :pm, proc { |obj|
  obj.methods.sort.each{ |m| puts m }
})

Defines a new p method on the base Object that does a standard ‘Kernel.p’ but also prints out the file and line number that called the ‘p’ method. This is really handy when you have finished developing/debugging a large section of code across many files and can’t quite find those last few debug lines that you need to remove. Anyone tried searching their source code for the search string “p”? 🙂

class Object
def p(*args)
Kernel.p args
puts “@ ” << caller[0].to_s end end [/sourcecode] Raising errors while parsing your own files/DSL? Help the developer out by including a key part of the stack trace when the exception was thrown and concatenating this method call on the end of the raise (in this case the .txt file that was being parsed): [sourcecode language='ruby'] def parse_error "This happened while parsing #{ caller.map{ |o| o.to_s.grep(/\.txt/) } }" end [/sourcecode]