user254694
user254694

Reputation: 1612

make object available in sinatra scope

In sinatra I have the following:

config = YAML.load_file('sinatra_resources/server.yml')
usernamedk = config["dkuser"]
passworddk = config["dkpass"]
passwordse = config["sepass"]
usernamese = config["seuser"]
database = config["database"]

cpooldk = OCI8::ConnectionPool.new(1, 5, 2, usernamedk, passworddk, database)
cpoolse = OCI8::ConnectionPool.new(1, 5, 2, usernamese, passwordse, database)

When I use any of these values in a route, it works fine. However I want to use them in a function and when I refer to these variables, etc.

As an example of my problem if I have a function

def getuser(lang)
 if lang == "se" then
   return usernamese
 else
   return usernamedk
end

and inside of a route I have user = getuser(lang)

then when I try to call it with lang = "se" I get that the variable usernamese is undefined.. the same thing applies to all the variables above which I want to use in a function shared between multiple routes.

I tried the following: configure do

set :env, "local"

set :usernamedk, config["dkuser"]
set :passworddk, config["dkpass"]
set :passwordse, config["sepass"]
set :usernamese, config["seuser"]
set :database, config["database"]

set :cpooldk, OCI8::ConnectionPool.new(1, 5, 2, setting.usernamedk, setting.passworddk, setting.database)
set :cpoolse,  OCI8::ConnectionPool.new(1, 5, 2, setting.usernamese, setting.passwordse, setting.database)

end

but I got back the error undefined local variable or method `usernamedk' for main:Object (NameError)

Upvotes: 1

Views: 1078

Answers (2)

ian
ian

Reputation: 12251

Why bother with all the variables when you have access to the config as a hash?

configure do
  # no need to set the env as local if you're trying to affect the scope

  config = YAML.load_file('sinatra_resources/server.yml')
  set :config, config

  set :cpooldk, OCI8::ConnectionPool.new(1, 5, 2, config["dkuser"], config["dkpass"], config["database"])
  set :cpoolse, OCI8::ConnectionPool.new(1, 5, 2, config["seuser"], config["sepass"], config["database"])
end

helpers do
  def getuser(lang)
    if lang == "se" then
      settings.config["seuser"] # no need for the explicit returns in Ruby
    else
      settings.config["dkuser"]
    end
  end
end

get "/some-route" do
  get_user("se")
end

Upvotes: 2

three
three

Reputation: 8478

You have only local scope for your vars, they are not instance vars. You could use them as instance variables by prefixing the @ such as @ usernamedk or you could use all these vars as settings (cf. https://github.com/sinatra/sinatra#configuration):

configure do
  set :usernamedk = config["dkuser"]
  set :passworddk = config["dkpass"]
  set :passwordse = config["sepass"]
  set :usernamese = config["seuser"]
  set :database = config["database"]
end

def getuser(lang)
  if lang == "se" then
    return settings.usernamese
  else
    return settings.usernamedk
end

Hope that helps

Upvotes: 1

Related Questions