我正在编写我的第一个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
当我在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 库。
将应用程序加载到 Pry 会话中:
查看你的 config.ru
文件。如果它的内容类似于以下内容:
require File.join(File.dirname(__FILE__), 'config', 'application.rb')
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,但与上述略有不同。在进程中运行的第一个文件之一,比如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
设置断点。这意味着我不需要改变任何代码就可以进入调试模式。