dsp_099
dsp_099

Reputation: 6121

How to make a DB connection available anywhere in sinatra without using globals?

Currently I have something like:

$db = Db::Connection.new()

then I use it like so:

get '/foo' do
 response.body = $db.fetch(params["bar"]) || ""
end

I was told by someone here on SO that this is not optimal.

Why and what should I do instead?

Upvotes: 0

Views: 277

Answers (1)

manadart
manadart

Reputation: 1810

In my configure do block I would put it in settings like this:

set :db, Db::Connection.new()

Then when you need it, get it thusly:

settings.db.fetch(params["bar"])

Or assign it to a local variable if you need to re-use it etc.

Upvotes: 1

Related Questions