开发者

Sharing a database connection with included classes in a Sinatra application

开发者 https://www.devze.com 2022-12-26 23:48 出处:网络
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.Wi

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开发者_StackOverflow社区? 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号