与 Sinatra 应用程序中包含的类共享数据库连接
我正在将 Rails 应用程序的一部分转换为其自己的 sinatra 应用程序。它有一些重要的工作要做,而不是在 app.rb 中提供一百万个帮助,我将其中一些分成了类。如果无法访问 Rails,我将重写 finder 的几种方法,并需要访问类中的数据库。在应用程序和类之间共享数据库连接的最佳方式是什么?或者您是否建议将所有数据库工作推入其自己的类中,并且仅在那里建立连接?
这是我在 app.rb 中的内容,
require 'lib/myclass'
configure :production do
MysqlDB = Sequel.connect('mysql://user:password@host:port/db_name')
end
我想在 lib/myclass.rb 中访问它,
class Myclass
def self.find_by_domain_and_stub(domain, stub)
# want to do a query here
end
end
我已经尝试了几件事,但似乎没有什么效果足以包含作为示例。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
蒂姆·罗森布拉特 (Tim Rosenblatt) 的回答将根据每个请求重新连接。最好在您的 Sinatra 应用程序中执行以下操作:
在这种情况下,最好使用常量而不是全局变量。
Tim Rosenblatt's answer will reconnect on every request. It's better to do the following in your Sinatra app:
It's better to use a constant than a global variable in this case.
假设您没有进行任何线程处理,只需将连接设置为全局变量即可。
检查连接超时设置或明确与服务器断开连接可能是明智之举。如果您正在处理大量请求,则可能会在超时之前耗尽连接。
Assuming you're not doing any threading, just set up the connection as a global var.
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.