I had a look at this question, but this is only for variables. I would like to create an object of a class and use it globally in Sinatra
I am doing something like the following and works fine:
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
But I would like to create the object outside the post. Maybe something like:
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
However, the latter does not work as I get null in the value.
How can I create the object once and then use it globally?