Ruby on Rails:如何找出调用方法的位置?
我正在快速了解现有的 Rails 项目,并且想知道模型 (ActiveRecord) 中的特定属性(字段)在哪里被修改。在 Java 中,我要么在 setter 上使用 Eclipse“查找引用”功能,要么在那里设置断点。对于 ActiveRecord,该属性甚至没有在类文件中列出!当然,我可以进行文本搜索并查看数百个结果,但这违背了使用 IDE 的意义。有更好的办法吗?我正在使用 RubyMine。
I am getting up to speed with an existing Rails project and am wondering where a particular attribute (field) in the model (ActiveRecord) is modified. In Java I would either use the Eclipse "find reference" feature on the setter, or set a breakpoint there. With the ActiveRecord, the attribute is not even listed in the class file! Of course I can do a text search and look through hundreds of results, but this defies the point of working with an IDE. Is there a better way? I'm using RubyMine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
tl;dr
Kernel.caller
说明
Rails 使用 method_missing 在 ActiveRecord 模型上实现属性方法。 您可以在 ActiveRecord::Base 源代码中看到这一点代码。 对于模型类 YourModel,我解决这个问题的方法如下:
实际上还有一些其他方法可以更新您的属性,例如 update_attribute 和朋友。如果您找不到分配调用站点,您可以继续重写方法,直到找到您的代码正在使用的方法。或者,您可以在 gem 的本地副本中更改 ActiveRecord::Base (“bundle show activerecord”给出了它的路径)。
tl;dr
Kernel.caller
Explanation
Rails uses method_missing to implement attribute methods on ActiveRecord models. You can see that in the ActiveRecord::Base source code. The way I would approach this problem for a model class YourModel is like so:
There are actually a few other ways that your attribute might get updated, such as update_attribute and friends. If you can't find the assignment call site you can keep overriding methods till you find that one that your code is using. Alternatively, you can alter ActiveRecord::Base in your local copy of the gem ("bundle show activerecord" gives the path to it).
RubyMine 具有类似于 eclipse 的查找参考功能。然而,它对于浏览 Rails 源代码没有太大帮助,因为 AR 使用了大量的元编程。查看查找结果时,您需要查看使用“send”的行以及对函数的裸调用。
您需要注意的另一件事是 AR 在运行时合成代码;您正在寻找的方法甚至可能不存在于源代码中。
RubyMine has a find reference feature like eclipse. However, it won't help much for navigating the Rails source as AR uses a lot of metaprogramming. When looking through the find results, you'll want to look at lines that use 'send' as well as bare calls to your function.
Another thing you will need to be aware of is that AR synthesizes code at runtime; the method you're looking for may not even be present in the source.