Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to debug third-party gems in ruby

Since there may be a lot of Ghost Methods inside a ruby gem, I don't think it is a good idea to study the inner mechanism of a ruby gem just by reading its source code statically. Is there a way to attach the source file of a third-part gem to a running ruby process for debugging so that I can set break point and see how things work dynamically ?
BTW,I've tried to navigate to the source file of a third-part gem in RubyMine by clicking on the context menu "Go To->Implementations" of the 'require' statement or other symbol of an third-part gem( require 'watir' for example ), without success. Is it normal for an IDE of a dynamic typing language such as Ruby to fail a symbol navigation?

like image 322
TomCaps Avatar asked Dec 17 '11 14:12

TomCaps


People also ask

How do I debug a ruby test?

First of all you must install ruby-debug. immediately before the line you wish to start debugging. Next step: run your unit tests as you would do normaly. At the moment that ruby reaches the line that contain the debugger directive it will stop and show you a console prompt.

How do you use Byebug in Ruby?

wherever you'd like the application to "break" - that is, executing byebug is equivalent to putting a breakpoint in your code. Run the program and use the debugger commands once you reach the breakpoint. near the end. Restart your server.


2 Answers

I would love to know if there's a better way to do this, but how I usually do it is:

  1. Add the ruby-debug gem to your Gemfile (or ruby-debug19 if you're on Ruby 1.9.2)
  2. Find the Gem by doing bundle show gemname. I'm on a Mac so I usually pipe this to pbcopy so it gets copied to my clipboard. bundle show rails | pbcopy
  3. Open the gem directory in your favorite editor. mvim /path/to/gem/directory
  4. Navigate to the file and line where you want to put the breakpoint* and insert debugger above the line in question.
  5. Reload page, run test, or do whatever you would to get the Gem file to execute
  6. When execution stops at debugger, you can inspect variables (p variable_name), and move line by line with the ruby debugger commands.

*Knowing where to put the breakpoint can take some understanding of the code, but you should start in lib/gemname.rb

like image 71
Peter Brown Avatar answered Oct 11 '22 12:10

Peter Brown


I would avoid editing the Gem files as suggested in the currently accepted answer. Instead, put the debugger command in one of your app files and use the break command to set a breakpoint in the gem. I'm using rvm with a gemset so here is how I do it:

break /Users/chris/.rvm/gems/ruby-1.9.3-p125@<gemset>/gems/<gem_name>-<gem-version>/<path_to_file>:<line_number>

like image 40
Chris Beck Avatar answered Oct 11 '22 12:10

Chris Beck