2015-09-14 108 views
0

我看了一下這個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值工作。

如何創建一個對象然後在全局使用它?

回答

1

如果你想有一個全局可訪問的變量,只要使用$符號:

$myobj = MyObject.new 
... more code 
$myobj.some_method 

然而,稍微更優雅的解決方案可能是沿着這些路線的東西:

require 'sinatra/base' 

class MyApp < Sinatra::Base 
    set :sessions, true 
    set :my_obj, MyObject.new 

    get '/' do 
    # call settings.my_obj 
    end 
end