How do I find where a ruby method is declared?

后端 未结 3 860
情深已故
情深已故 2020-12-29 09:40

I have a ruby method (deactivate!) that is on an activeRecord class. However, I can\'t seem to find where that method is declared.

There have been numerous develope

相关标签:
3条回答
  • 2020-12-29 10:03

    First question would be: is it an actual method? Does obj.method(:deactivate!) raise an error?

    If it doesn't, then you can use Method#source_location(in Ruby 1.9 only, and backports can't support it):

    obj.method(:deactivate!).source_location
    

    If it does raise a NoMethodError, it is handled via method_missing. This makes it hard to track. If it accepts arguments, I'd try sending the wrong type and using the backtrace of the raised exception.

    Are you using state_machine? If you have an event transition called :deactivate, the model will have the method #deactivate! created automatically.

    0 讨论(0)
  • 2020-12-29 10:08

    As a first stab, try the Jump to Declaration feature of your IDE. Depending on how good your IDE's static type inference is, it should take you right there.

    If that doesn't work, set a breakpoint on that call, fire up the debugger and step into the method.

    0 讨论(0)
  • 2020-12-29 10:13

    When I need to find where a method is declared on some class, say 'Model', I do

    Model.ancestors.find {|c| c.instance_methods(false).include? :deactivate! }
    

    This searches the ancestor tree in the same order that ruby does for the first that has the method in instance_methods(false), which only includes non-inherited methods.

    Note: before ruby 1.9, the methods were listed as strings not symbols, so it would be

    Model.ancestors.find {|c| c.instance_methods(false).include?('deactivate!') }
    
    0 讨论(0)
提交回复
热议问题