Sharing a connection with included classes in a Sinatra application
I am converting part of rails app to my own sinatra app. It has some promising work to do, and instead of a million help in app.rb, I've split some of that into classes. Without access to rails, I am rewriting finder several methods and need access to the database inside my class. What is the best way to share a database connection between your application and the class? Or would you recommend pushing all the database work into your own class and only making a connection there?
Here is what I found in app.rb
require 'lib/myclass'
configure :production do
MysqlDB = Sequel.connect('mysql://user:password@host:port/db_name')
end
I want to access it in lib / myclass.rb
class Myclass
def self.find_by_domain_and_stub(domain, stub)
# want to do a query here
end
end
I've tried a few things, but nothing that seems to work well enough to even include as an example.
a source to share
Assuming you are not threading, just set up the connection as a global var.
require 'lib/myclass'
before do
$MysqlDB = Sequel.connect('mysql://user:password@host:port/db_name')
end
class Myclass
def self.find_by_domain_and_stub(domain, stub)
# use $MysqlDB here
end
end
It might be wise to check your connection timeout settings or explicitly disconnect from the server. If you are handling a lot of requests, you may run out of connections before they time out.
a source to share
Tim Rosenblatt's answer will be reconnected to every request. Better to do the following in your Sinatra application:
require 'sequel'
DB = Sequel.connect('mysql://user:password@host:port/db_name')
require 'lib/myclass'
In this case, it is better to use a constant than a global variable.
a source to share