【发布时间】:2011-11-03 02:28:19
【问题描述】:
我正在编写我的第一个 Sinatra 应用程序,并希望使用 Pry 来检查/调试应用程序中发生的一些事情。我以前也没有使用过 Pry,但我想尝试一下。如何开始在我的 Sinatra 应用程序中使用 Pry?
【问题讨论】:
我正在编写我的第一个 Sinatra 应用程序,并希望使用 Pry 来检查/调试应用程序中发生的一些事情。我以前也没有使用过 Pry,但我想尝试一下。如何开始在我的 Sinatra 应用程序中使用 Pry?
【问题讨论】:
require 'pry'。binding.pry。有关使用 Pry 的信息,请参阅 Turning IRB on its head with Pry 和 Pry wiki。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
当我在网络浏览器中向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 库。
【讨论】:
我更喜欢 pry-debugger。但是仍然有一个窍门,那就是在经典风格下运行 sinatra 时不能撬动。
为了找到调试 sinatra 应用程序的最佳方法,我在 github 上创建了一个 repo,如下所示。
【讨论】:
将应用程序加载到 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 使用的高级示例。
【讨论】:
我的首选方法也是 Pry,但与上面的方法有点不同。在进程中运行的第一个文件中,例如 config.ru 或 spec/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 设置断点。这意味着我根本不需要更改代码即可投入其中。
【讨论】: