Get class location from class object

后端 未结 7 2167
北恋
北恋 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:17

    Here's a simple example showing how I track locations in code. If I need to know a location in a module:

    class Foo
      attr_reader :initialize_loc
      def initialize
        @initialize_loc = [__FILE__, __LINE__]
        # do more stuff...
      end
    end
    

    If I need to know where something happened:

    require_relative 't1'
    
    foo = Foo.new
    # do lots of stuff until you want to know where something was initialized.
    puts 'foo initialized at %s:%s' % foo.initialize_loc
    

    When I run the code I get:

    FooBar:Desktop foobar ruby t2.rb 
    foo initilized at /Users/foobar/Desktop/t1.rb:4
    

    If I don't want to mess with the source-code of the module, and want the debugger to jump in when I need it, I'll have the debugger do just that:

    require_relative 't1'
    require 'ruby-debug'
    
    debugger
    foo = Foo.new
    # do lots of stuff until you want to know where something was initilized.
    puts 'foo initilized at %s:%s' % foo.initialize_loc
    

    The execution will stop and I'll drop into the debugger at the line immediately following debugger:

    [0, 9] in t2.rb
      1  require_relative 't1'
      2  require 'ruby-debug'
      3  
      4  debugger
    => 5  foo = Foo.new
      6  # do lots of stuff until you want to know where something was initilized.
      7  puts 'foo initilized at %s:%s' % foo.initialize_loc
      8  
    t2.rb:5
    foo = Foo.new
    (rdb:1) 
    

    A simple s will "step" me into the next line of code, which will be in the initialize block for Foo:

    (rdb:1) s
    [-1, 8] in /Users/foobar/Desktop/t1.rb
      1  class Foo
      2    attr_reader :initialize_loc
      3    def initialize
    => 4      @initialize_loc = [__FILE__, __LINE__]
      5      # do more stuff...
      6    end
      7  end
      8  
    /Users/foobar/Desktop/t1.rb:4
    @initialize_loc = [__FILE__, __LINE__]
    (rdb:1) 
    

    Beyond this, using tools like grep -rn target_to_find path_to_search to recursively search directories and list the filename and line numbers of lines matching the target, will go a long ways to helping find what you're looking for.

    Or, using :vim /target_to_find/ path_to_search from inside Vim will return the files you're looking for.

提交回复
热议问题