我查看了这个question,但这仅适用于变量。我想创建一个类的对象,并在Sinatra
中全局使用它我正在做类似以下的事情并且工作正常:
require 'sinatra'
require 'MyClass'
set :port, 8080
set :static, true
get '/' do
erb :myform, :locals => {'value' => "Give a value."}
end
post '/hello/' do
param_1 = params[:param_1]
param_2 = params[:param_2]
@obj = MyClass.new
value = @obj.run(param_1, param_2)
erb :myform, :locals => {'value' => value}
end
但是我想在帖子之外创建对象。也许是这样的:
require 'sinatra'
require 'MyClass'
set :port, 8080
set :static, true
@obj = MyClass.new
get '/' do
erb :myform, :locals => {'value' => "Give a value."}
end
post '/hello/' do
param_1 = params[:param_1]
param_2 = params[:param_2]
value = @obj.run(param_1, param_2)
erb :myform, :locals => {'value' => value}
end
然而,后者不起作用,因为我在值中得到null。
如何创建对象一次然后全局使用?