How do I step out of a loop with Ruby Pry?

前端 未结 9 1074
醉话见心
醉话见心 2020-12-22 15:11

I\'m using Pry with my Rails application. I set binding.pry inside a loop in my model to try and debug a problem. For example:

(1..100).each do          


        
相关标签:
9条回答
  • 2020-12-22 15:30

    Use

    disable-pry
    

    To renable, add this to your controller

    ENV['DISABLE_PRY'] = nil
    
    0 讨论(0)
  • press 'q' and you will see just like this

    [1] pry(#<AlbumsController>)>
    

    type

    exit
    

    this one word will do, if not:

    control + c
    
    0 讨论(0)
  • 2020-12-22 15:45

    A binding.pry statement is exactly the same as a breakpoint in GDB. Such a breakpoint in GDB would be hit 100 times too.

    If you only want the binding.pry to be hit once, for the first iteration of the loop, then use a conditional on the binding.pry like so:

    (1..100).each do |i|
      binding.pry if i == 1
      puts i
    end
    

    You then exit the current session by just typing exit.

    0 讨论(0)
  • 2020-12-22 15:47

    I use:

    disable-pry
    

    This will keep the program running, but will keep it from continuing to stop execution. This is especially helpful when you are debugging in the console.

    0 讨论(0)
  • 2020-12-22 15:49

    Using gem pry-moves you can step out of loop using f (finish command)


    example:

        42: def test
        43:   3.times do |i|
     => 44:     binding.pry
        45:     puts i
        46:   end
        47:   puts :finish
        48: end
    
    [1] pry(main)> f
    0
    1
    2
    
    Frame: 0/1 method
    From: playground/sand.rb:47 main
    
        42: def test
        43:   3.times do |i|
        44:     binding.pry
        45:     puts i
        46:   end
     => 47:   puts :finish
        48: end
    
    0 讨论(0)
  • 2020-12-22 15:50

    Based on the two previous answers above:

    • https://stackoverflow.com/a/21735420/3137698
    • https://stackoverflow.com/a/24945487/3137698

    Thank you guys! Your advices have helped me really a lot!

    I just want to share a simple stupid trick, that I personally use to don't worry about the DISABLE_PRY environment variable all the time. Add this callback to the base controller ApplicationController of your project permanently. It would automatically re-enable PRY every time the disable-pry is called:

    # app/controllers/application_controller.rb
    class ApplicationController < ActionController::Base
      before_action :reenable_pry
    
      private
    
      def reenable_pry
        ENV['DISABLE_PRY'] = nil
      end
    end
    
    0 讨论(0)
提交回复
热议问题