Really useful Rails/Ruby debug helper functions

June 4, 2008 § Leave a comment

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

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):

def parse_error
  "This happened while parsing #{ caller.map{ |o| o.to_s.grep(/\.txt/) } }"
end

Original post: Really useful Rails/Ruby debug helper functions.

Advertisements

Tagged: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Really useful Rails/Ruby debug helper functions at Fringley's Blog.

meta

%d bloggers like this: