Transactions in Ruby Sequel module: how to get DB

2020-07-30 04:30发布

问题:

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