Sharing a database connection with included classes in a Sinatra application

I'm converting a part of a rails application to its own sinatra application. It has some beefy work to do and rather than have a million helps in app.rb, I've separated some of it out into classes. Without access to rails I'm rewriting finder several methods and needing access to the database inside of my class. What's the best way to share a database connection between your application and a class? Or would you recommend pushing all database work into its own class and only having the connection established there?

Here is what I have in 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 several things but nothing that seems to work well enough to even include as an example.

Upvotes: 2

Views: 1879

Answers (2)

Jeremy Evans
Jeremy Evans

Reputation: 12149

Tim Rosenblatt's answer will reconnect on every request. It's better to do the following in your Sinatra app:

require 'sequel'
DB = Sequel.connect('mysql://user:password@host:port/db_name')
require 'lib/myclass'

It's better to use a constant than a global variable in this case.

Upvotes: 3

Tim Rosenblatt
Tim Rosenblatt

Reputation: 171

Assuming you're not doing any 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

Might be wise to check the connection timeout settings, or explicitly disconnect from the server. If you're handling a lot of requests, you could run out of connections before they time out.

Upvotes: 3

Related Questions