Get class location from class object

后端 未结 7 2074
北恋
北恋 2020-12-13 23:29

I have a bunch of code to look at, and now it is debugging time. Since I have never been a fan of Ruby\'s debugger I am looking for a way of going through code and reading i

相关标签:
7条回答
  • 2020-12-14 00:28

    For Methods and Procs Ruby 1.9 has method called source_location:

    Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)

    So you can request for the method:

    m = Foo::Bar.method(:create)
    

    And then ask for the source_location of that method:

    m.source_location
    

    This will return an array with filename and line number. E.g for ActiveRecord::Base#validates this returns:

    ActiveRecord::Base.method(:validates).source_location
    # => ["/Users/laas/.rvm/gems/ruby-1.9.2-p0@arveaurik/gems/activemodel-3.2.2/lib/active_model/validations/validates.rb", 81]
    

    For classes and modules, Ruby does not offer built in support, but there is an excellent Gist out there that builds upon source_location to return file for a given method or first file for a class if no method was specified:

    • ruby where_is module

    EDIT: For Ruby 1.8.7 there is a gem that backports source_location:

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