我想在每次击中网址/代码时运行脚本(code.rb)。
如何运行脚本?
require 'sinatra'
get '/' do
#run the script
end
答案 0 :(得分:8)
要么分叉另一个过程:
system('ruby code.rb')
...或只是load
脚本进入当前上下文:
load 'code.rb' # *not* require
答案 1 :(得分:6)
您需要load
代码以确保每次都运行它; require
只会在第一次请求时加载一次代码,然后不再加载:
smagic:Desktop phrogz$ cat hi.rb
puts "hi"
smagic:Desktop phrogz$ cat test.rb
require 'sinatra'
get '/require' do
x = require_relative( 'hi.rb' )
"require sez #{x}"
end
get '/load' do
x = load( 'hi.rb' )
"load sez #{x}"
end
smagic:Desktop phrogz$ ruby test.rb
== Sinatra/1.1.2 has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.2.7 codename No Hup)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:4567, CTRL+C to stop
hi
127.0.0.1 - - [16/Jan/2011 20:49:43] "GET /require HTTP/1.1" 200 16 0.0019
127.0.0.1 - - [16/Jan/2011 20:49:46] "GET /require HTTP/1.1" 200 17 0.0005
hi
127.0.0.1 - - [16/Jan/2011 20:49:52] "GET /load HTTP/1.1" 200 13 0.0009
hi
127.0.0.1 - - [16/Jan/2011 20:49:54] "GET /load HTTP/1.1" 200 13 0.0008
127.0.0.1 - - [16/Jan/2011 20:50:09] "GET /require HTTP/1.1" 200 17 0.0005
127.0.0.1 - - [16/Jan/2011 20:50:12] "GET /require HTTP/1.1" 200 17 0.0005
hi
的输出位于日志中的请求条目之前;您可以看到“要求”的请求仅在第一次输出hi
时,而“加载”请求每次都会显示hi
。这是服务器的输出,其中true
表示文件中的代码实际运行,false
表明它不是:
smagic:~ phrogz$ curl http://localhost:4567/require
require sez true
smagic:~ phrogz$ curl http://localhost:4567/require
require sez false
smagic:~ phrogz$ curl http://localhost:4567/load
load sez true
smagic:~ phrogz$ curl http://localhost:4567/load
load sez true
smagic:~ phrogz$ curl http://localhost:4567/require
require sez false
smagic:~ phrogz$ curl http://localhost:4567/require
require sez false