Module: WdSinatraSequel::DBConnector

Defined in:
lib/wd_sinatra_sequel.rb

Overview

DB Connection ########

Constant Summary collapse

DB_FILE =
File.join(WDSinatra::AppLoader.root_path, "config", "database.yml")
DB_CONFIG =
YAML.load_file(DB_FILE)

Class Method Summary collapse

Class Method Details

.connect_to_dbObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/wd_sinatra_sequel.rb', line 70

def connect_to_db
  if @db_configuration
    if @db_configuration.has_key?('uri')
      uri = @db_configuration['uri']
      config_without_uri = @db_configuration.clone
      config_without_uri.delete('uri')
      connection = Sequel.connect(uri, config_without_uri)
    else
      connection = Sequel.connect(@db_configuration)
    end
  else
    raise "Can't connect without the config previously set"
  end
end

.db_configuration(env = RACK_ENV) ⇒ Object



58
59
60
61
62
63
# File 'lib/wd_sinatra_sequel.rb', line 58

def db_configuration(env=RACK_ENV)
  old_connect_status = ENV['DONT_CONNECT']
  set_db_connection(env)
  ENV['DONT_CONNECT'] = old_connect_status
  @db_configuration
end

.db_configurationsObject



65
66
67
68
# File 'lib/wd_sinatra_sequel.rb', line 65

def db_configurations
  db_configuration unless @db_configurations
  @db_configurations
end

.set_db_connection(env = RACK_ENV) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/wd_sinatra_sequel.rb', line 27

def set_db_connection(env=RACK_ENV)
  # Set the Sequel logger
  loggers = []
  if Object.const_defined?(:LOGGER)
    loggers << LOGGER
  else
    loggers << Logger.new($stdout)
  end

  # Establish the DB connection
  if File.exist?(DB_FILE)
    if DB_CONFIG && DB_CONFIG[env]
      @db_configurations = DB_CONFIG
      @db_configuration = @db_configurations[env]
      # add loggers
      @db_configuration['loggers'] ||= []
      @db_configuration['loggers'].concat(loggers)
      # overwrite DB name by using an ENV variable
      if ENV['FORCED_DB_NAME']
        print "Database name overwritten to be #{ENV['FORCED_DB_NAME']}\n"
        @db_configurations[env]['database'] = @db_configuration['database'] = ENV['FORCED_DB_NAME']
      end
      connect_to_db unless ENV['DONT_CONNECT']
    else
      raise "#{DB_FILE} doesn't have an entry for the #{env} environment"
    end
  else
    raise "#{DB_FILE} file missing, can't connect to the DB"
  end
end