0

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?

Community
  • 1
  • 1
Galil
  • 859
  • 2
  • 16
  • 40

1 Answers1

1

If you want a globally accessible variable, just use the $ notation:

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

However, a slightly more elegant solution might be something along these lines:

require 'sinatra/base'

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

  get '/' do
    # call settings.my_obj
  end
end
Zohar Arad
  • 88
  • 1
  • 5