Skip to content

Instantly share code, notes, and snippets.

@ma2shita
Created December 5, 2014 01:09
Show Gist options
  • Save ma2shita/e4c96cc36fb8feb6bdd0 to your computer and use it in GitHub Desktop.
Save ma2shita/e4c96cc36fb8feb6bdd0 to your computer and use it in GitHub Desktop.
Reconnect to DB module using Sequel
require "singleton"
require "sequel"
=begin
Overview:
Reconnect to DB module using Sequel
When `ping` success, `connection` return same connection.
In case of fail, reload `config/database.yml` and try new connect.
Require:
`../config/database.yml` (Deploy in `lib/` (or other dir) this file.)
Usage:
require "lib/THIS_FILE.rb"
DB::Connector.instance.connection
=> #<Sequel::**::Database>
a = DB::Connector.instance
a.connection[:items]
=> <Sequel::**::Dataset: "SELECT * FROM \"items\"">
# using Sequel::Model
Sequel:Model.db = DB::Connector.instance.connection
Advanced(for short hand):
require "lib/THIS_FILE.rb"
include DB
db
=> #<Sequel::**::Database>
db[:items]
=> <Sequel::**::Dataset: "SELECT * FROM \"items\"">
** WARNING: If variable assign to `db`, it cannot use after. **
db
=> #<Sequel::**::Database>
db = 1
db
=> 1 (Oh... T_T)
Limit:
Under run the PostgreSQL only. (TDB)
config/database.yml:
development:
adapter: postgres
host: 127.0.0.1
username: postgres
password: postgres
database: development_db
min_messages: warn
test:
adapter: postgres
host: 127.0.0.1
username: postgres
password: postgres
database: test_db
min_messages: warn
=end
module DB
class Connector
include Singleton
def initialize
@c = File.join(File.expand_path(File.dirname(__FILE__)), "..", "config", "database.yml")
end
def ping
@db[:pg_attribute].first
true
end
def connection
begin
ping
rescue
dbconf = YAML.load(ERB.new(File.read(@c)).result)
@db = Sequel.connect(dbconf[Sinatra::Base.environment.to_s])
end
@db
end
end
def db
DB::Connector.instance.connection
end
module_function :db
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment