如何与Sinatra一起使用Pry?

时间:2011-08-24 19:12:21

标签: ruby sinatra pry

我正在编写我的第一个Sinatra应用程序,并希望使用Pry来检查/调试应用程序中正在发生的一些事情。我之前没有使用过Pry,但我想尝试一下。我如何开始在我的Sinatra应用程序中使用Pry?

4 个答案:

答案 0 :(得分:51)

摘要

  1. 在应用程序顶部使用require 'pry'
  2. 只要您想要进入交互式会话,就可以在代码中调用binding.pry。有关使用Pry的信息,请参阅Turning IRB on its head with PryPry wiki
  3. 完成特定的交互式会话后,键入exit或Ctrl-D; Sinatra将从中断的地方恢复运行。
  4. 实施例

    require 'sinatra'
    require 'pry'
    
    get '/' do
      @cats = rand(100)
      html = haml :index
      binding.pry
      html
    end
    
    __END__
    @@index
    %html
      <head><title>Hello World</title></head>
      %body
        %p I have #{@cats} cat#{:s unless @cats==1}!
    

    以下是我启动Web服务器时的样子:

    C:\>ruby pry_into_sinatra.rb
    == Sinatra/1.2.6 has taken the stage on 4567 for development with backup from Thin
    >> Thin web server (v1.2.11 codename Bat-Shit Crazy)
    >> Maximum connections set to 1024
    >> Listening on 0.0.0.0:4567, CTRL+C to stop
    

    当我在网络浏览器中向http://localhost:4567发出请求时,控制台会在发送结果之前进入Pry调试器:

    From: pry_into_sinatra.rb @ line 7 in Sinatra::Application#HEAD /:
    
         2: require 'pry'
         3:
         4: get '/' do
         5:         @cats = rand(100)
         6:         html = haml :index
     =>  7:         binding.pry
         8:         html
         9: end
        10:
        11: __END__
        12: @@index
    pry(#<Sinatra::Application:0x3300ac8>)> @cats
    => 42
    pry(#<Sinatra::Application:0x3300ac8>)> puts html
    <html>
      <head><title>Hello World</title></head>
      <body>
        <p>I have 42 cats!</p>
      </body>
    </html>
    => nil
    pry(#<Sinatra::Application:0x3300ac8>)> exit
    127.0.0.1 - - [24/Aug/2011 13:25:57] "GET / HTTP/1.1" 200 96 28.5390
    127.0.0.1 - - [24/Aug/2011 13:25:57] "GET /favicon.ico HTTP/1.1" 404 447 0.0010
    

    进一步调试

    如果您希望能够使用传统的调试命令,例如设置基于行的断点或步进,或者在引发异常时中断,请参阅Mon-Ouie的PryDebug库。

答案 1 :(得分:6)

将应用程序加载到Pry会话中:

看看你的config.ru。如果它看起来像这样:

require File.join(File.dirname(__FILE__), 'config', 'application.rb')

您可以使用

将应用程序加载到Pry中
bundle exec pry -I . -r config/application.rb
# where -I . adds current dir to load path
# and -r is the file you want to require

只要满足依赖关系,就可以使用任何模块或类完成此操作。

请查看此Pry cheat sheet以获取Pry使用的高级示例。

答案 2 :(得分:4)

我更喜欢pry-debugger。然而,仍然有一些技巧,当你在经典风格下运行sinatra时,你不能撬开。

为了找到调试sinatra app的最佳方法,我在github创建了一个repo,如下所示。

enter image description here

以下是回购:https://github.com/hlee/sinatra_debugger_example

答案 3 :(得分:0)

我首选的方法也是Pry,但与上面略有不同。在要在进程中运行的第一个文件中,说config.ruspec/spec_helper.rb

if ENV["DEBUG"]
  require 'pry-byebug'
  # and any other Pry extensions etc
  binding.pry
end

然后,如果要使用调试,请运行env DEBUG=1 bin/rackup config.ruenv DEBUG=1 bin/rspec(我在RSpec中经常使用-e开关使用它),然后使用{{1 }}。这意味着我完全不必更改代码即可放入其中。