Best way to debug third-party gems in ruby

前端 未结 5 1401
孤独总比滥情好
孤独总比滥情好 2020-12-07 18:06

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

相关标签:
5条回答
  • 2020-12-07 18:14

    If you are using visual studio code, and you have normal debugging enabled for rails you can just open the gem file you want to debug in VS Code, example:

    C:\Ruby26-x64\lib\ruby\gems\2.6.0\gems\devise-4.7.3\app\controllers\devise\registrations_controller.rb
    

    and set a breakpoint with VSCode. It will stop execution on that line.

    0 讨论(0)
  • 2020-12-07 18:19

    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>

    0 讨论(0)
  • 2020-12-07 18:21

    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

    0 讨论(0)
  • 2020-12-07 18:24

    In languages that change the code at runtime, like Ruby, it is hard to accurately predict 100% the origins of symbols, methods etc.

    I deal with a lot of third party gems that need source code analysis and I found that the best tool for this task is Netbeans + its Ruby and Rails plugin.

    • allows good navigation in the dependent gems source code (unlike other alternatives)
    • visual breakpoints and debugging that actually work (with trace and all) **

    ** it has some glitches with method calls in yielded code blocks (like each {}) but I learned to deal with those.

    What I usually do is set breakpoints and analyse the code at runtime.

    0 讨论(0)
  • 2020-12-07 18:27

    Both commands output a path to the gem source in your computer.

    # if it is present in your gemfile
    bundle show gemname
    
    # if not in your gemfile
    gem which gemname
    

    Then just open the folder in your text editor of choice, and good debugging!

    0 讨论(0)
提交回复
热议问题