Is there a way to use a keystroke to invoke the pry ruby gem?

送分小仙女□ 提交于 2020-01-01 18:43:10

问题


I was just thinking about how great it would be to be able to run a program and then hit a keystroke to invoke pry and debug. Maybe there is a gem out there that injects binding.pry dynamically during runtime that I don't know about. If there isn't, how would you make a keystroke that inserts binding.pry before the next line of ruby script that is about to execute?


回答1:


Assuming a POSIX OS, you could try adding a signal handler in your ruby program. The ruby documentation even gives an example of your use case:

.. your process may trap the USR1 signal and use it to toggle debugging (http://www.ruby-doc.org/core-2.1.3/Signal.html)

Signal.trap('USR1') do
  binding.pry
end

Then, to send the signal:

kill -s SIGUSR1 [pid]

Edit: A more complete example: application.rb

My naïve suggestion above will fail with a ThreadError: current thread not owner. Here's a better example using a global $debug flag.

#!/usr/bin/env ruby

require 'pry'

$debug = false
Signal.trap('USR1') do
  puts 'trapped USR1'
  $debug = true
end

class Application
  def run
    while true
      print '.'
      sleep 5
      binding.pry if $debug
    end
  end
end

Application.new.run

This seems to work best when application.rb is running in the foreground in one shell, and you send the SIGUSR1 signal from a separate shell.

Tested in Mac OS 10.9.5. YMMV.



来源:https://stackoverflow.com/questions/26384563/is-there-a-way-to-use-a-keystroke-to-invoke-the-pry-ruby-gem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!