Module: Whatup::Server::DbInit

Extended by:
Redirection, WhatupLogger
Included in:
Server
Defined in:
lib/whatup/server/db_init.rb

Class Method Summary collapse

Methods included from Redirection

redirect

Methods included from WhatupLogger

log

Class Method Details

.setup_db!Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/whatup/server/db_init.rb', line 14

def setup_db!
  log.debug { 'Setting up database ...' }

  db = "#{Dir.home}/.whatup.db"

  if File.exist?(db)
    log.debug { "Using existing database `#{db}" }
  else
    log.debug { "Creating new database `#{db}" }
    SQLite3::Database.new(db)
  end

  ActiveRecord::Base.establish_connection adapter: 'sqlite3',
                                          database: db

  truncate_sql = <<~SQL
    DROP TABLE IF EXISTS clients_rooms;
    DROP TABLE IF EXISTS clients;
    DROP TABLE IF EXISTS messages;
    DROP TABLE IF EXISTS rooms;
  SQL
  log.debug { "Truncating existing data ...\n#{truncate_sql}" }
  ActiveRecord::Base.connection.execute truncate_sql

  StringIO.new.tap do |io|
    redirect(stdout: io) { create_tables! }
    log.debug { "Creating tables ...\n#{io&.string}" }
  end
end