问题描述
由于 ruby gem 内部可能有很多 Ghost Methods,所以我认为仅通过静态读取其源代码来研究 ruby gem 的内部机制不是一个好主意.有没有办法将第三方 gem 的源文件附加到正在运行的 ruby 进程进行调试,以便我可以设置断点并查看事情是如何动态工作的?
顺便说一句,我试图通过单击require"语句的上下文菜单Go To->Implementations"或第三方 gem 的其他符号来导航到 RubyMine 中第三方 gem 的源文件(require 'watir'
例如),但没有成功.对于 Ruby 等动态类型语言的 IDE,符号导航失败是否正常?
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?
推荐答案
我很想知道是否有更好的方法来做到这一点,但我通常是这样做的:
I would love to know if there's a better way to do this, but how I usually do it is:
- 将 ruby-debug gem 添加到您的 Gemfile(或 ruby-debug19,如果您使用的是 Ruby 1.9.2)
- 通过
bundle show gemname
找到 Gem.我在 Mac 上,所以我通常将其通过管道传输到 pbcopy,以便将其复制到我的剪贴板.bundle show rails |pbcopy
- 在您喜欢的编辑器中打开 gem 目录.
mvim/path/to/gem/directory
- 导航到要放置断点的文件和行*,然后在相关行上方插入
debugger
. - 重新加载页面、运行测试或执行任何您想要执行 Gem 文件的操作
- 当在调试器处停止执行时,您可以检查变量(
p variable_name
),并使用 ruby 调试器命令.
- Add the ruby-debug gem to your Gemfile (or ruby-debug19 if you're on Ruby 1.9.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
- Open the gem directory in your favorite editor.
mvim /path/to/gem/directory
- Navigate to the file and line where you want to put the breakpoint* and insert
debugger
above the line in question. - Reload page, run test, or do whatever you would to get the Gem file to execute
- When execution stops at debugger, you can inspect variables (
p variable_name
), and move line by line with the ruby debugger commands.
*知道断点在哪里可能需要对代码有所了解,但你应该从 lib/gemname.rb 开始
*Knowing where to put the breakpoint can take some understanding of the code, but you should start in lib/gemname.rb
这篇关于在 ruby 中调试第三方 gem 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!