Transactions in Ruby Sequel module: how to get DB object?

跟風遠走 提交于 2019-12-22 00:26:59

问题


I'm working in a Sinatra application using Sequel.

I want to make a transaction, according to the manual I have to use the DB object, how can I get this object from any part of my code?


回答1:


You can define it in your base app.rb (or equivalent) or include a separate file where you configure the DB object if you wish.

For example, in one of my Sinatra apps, I have an app.rb that includes a

class App < Sinatra::Application
  #lots of stuff here...
end

require_relative 'models/init'

In my models/init.rb I configure DB

require 'sequel'

conf = YAML.load(File.open(File.expand_path('./config/dbconn.yml')))
env = ENV['RACK_ENV'] || 'development'
DB = Sequel.connect(host:conf['database'][env]['host'],
                    port:conf['database'][env]['port'],
                    database:conf['database'][env]['schema'],
                    username:conf['database'][env]['username'],
                    password:conf['database'][env]['password'],
                    adapter:conf['database'][env]['adapter'],
                    encoding:conf['database'][env]['encoding'])
raise "Unable to connect to #{conf['database'][env]['host']}" unless DB.test_connection

...

That's one way. Hope it helps.




回答2:


You mention that you want to reference from any part of your code; however I've found that encapsulated within the models is where I tend to wrap transactions; and from there it's relatively easy:

class X < Sequel::Model
  def self.y
    self.db.transaction {
    ...
    end
  end
  def z
    db.transaction {
    ...
    }
  end
end  


来源:https://stackoverflow.com/questions/13593295/transactions-in-ruby-sequel-module-how-to-get-db-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!