How to create a global connection object with mongodb in Sinatra?

Using the ruby ​​mongodb driver, is there a way to create a connection object in the configure block that can be accessed in the route methods so that I do not need to recreate the connection for each request?

+4
source share
1 answer

Set the global variable in the configuration block:

configure do $mongo = Mongo::Connection.new end 

or paste it into settings :

 configure do set :mongo, Mongo::Connection.new end get '/' do # the connection is available through settings.mongo end 

I must say that I do not find any of these very elegant.

When developing internally, it may look like a connection is created for each request, but start your server during the production process and you will see that it behaves differently (for example, thin -e production ).

In addition, if your application will work under Passenger, you need to do this:

  configure do if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| if forked # *** reconnect to the database here! *** end end end end 

What he does is that he connects to the database again after the Passenger forks, so that the child processes have their own connection. Not doing this will give you really strange mistakes.

+6
source

All Articles