Ruby on Rails: how do I find out where a method is called?
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开发者_如何学Python working with an IDE. Is there a better way? I'm using RubyMine.
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:
class YourModel < ActiveRecord::Base
def myfield=(*args)
Rails.logger.debug "myfield called at #{Kernel.caller.inspect}"
super(*args)
end
end
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 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.
精彩评论