如何在Sinatra中使用Pry?

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

53

摘要

  1. 在应用程序的顶部使用 require 'pry'
  2. 在代码中使用 binding.pry,每当你想进入交互式会话时。有关使用Pry的信息,请参见Turning IRB on its head with PryPry wiki
  3. 当你完成特定的交互式会话后,输入 exit 或 Ctrl-D;Sinatra将恢复运行到离开的地方。

示例

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

当我在Web浏览器中请求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 库。


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速查表,了解Pry用法的高级示例。

4
我更喜欢使用pry-debugger。然而,仍有一个技巧,即在经典风格下运行sinatra时无法进行pry-stepping。
为了找到调试sinatra应用程序的最佳方法,我在github上创建了一个存储库,如下所示。

enter image description here

这里是代码库链接:https://github.com/hlee/sinatra_debugger_example


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.ru或者env DEBUG=1 bin/rspec(我在RSpec中经常使用-e开关),然后使用break设置断点。这意味着我不需要改变任何代码就可以进入调试模式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接