Search code examples
rubysinatrasequel

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


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?


Solution

  • 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.