Class: Database

Inherits:
Object
  • Object
show all
Defined in:
lib/reloj/orm/pg_db.rb

Class Method Summary collapse

Class Method Details

.configObject



27
28
29
# File 'lib/reloj/orm/pg_db.rb', line 27

def self.config
  @config ||= YAML.load_file(File.join(Dir.pwd, 'config/db.yml'))
end

.createObject



7
8
9
10
# File 'lib/reloj/orm/pg_db.rb', line 7

def self.create
  db = PG::Connection.new(dbname: "postgres")
  db.exec("CREATE DATABASE #{config[:dbname]}")
end

.deleteObject



12
13
14
15
# File 'lib/reloj/orm/pg_db.rb', line 12

def self.delete
  db = PG::Connection.new(dbname: "postgres")
  db.exec("DROP DATABASE IF EXISTS #{config[:dbname]}")
end

.execute(*args) ⇒ Object



54
55
56
57
# File 'lib/reloj/orm/pg_db.rb', line 54

def self.execute(*args)
  pretty_print_sql(*args)
  instance.exec(*args)
end

.instanceObject



48
49
50
51
52
# File 'lib/reloj/orm/pg_db.rb', line 48

def self.instance
  set_db if @db.nil?

  @db
end

.parse_params(params) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/reloj/orm/pg_db.rb', line 31

def self.parse_params(params)
  {
    host: params.host,
    dbname: params.path[1..-1],
    port: params.port,
    password: params.password,
    user: params.user
  }
end

.pretty_print_sql(*sql_args) ⇒ Object



59
60
61
62
63
64
# File 'lib/reloj/orm/pg_db.rb', line 59

def self.pretty_print_sql(*sql_args)
  pretty = sql_args.map do |a|
    a.is_a?(String) ? a.gsub(/\s+/, " ").gsub(/;\s/, ";\n") : a.join(", ")
  end.join("\n")
  print "\n#{pretty}\n"
end

.resetObject



22
23
24
25
# File 'lib/reloj/orm/pg_db.rb', line 22

def self.reset
  self.delete
  self.create
end

.set_dbObject



41
42
43
44
45
46
# File 'lib/reloj/orm/pg_db.rb', line 41

def self.set_db
  params = ENV["DATABASE_URL"] && URI.parse(ENV["DATABASE_URL"])
  db_options = params.nil? ? config : parse_params(params)

  @db ||= PG::Connection.new(db_options)
end

.setupObject



17
18
19
20
# File 'lib/reloj/orm/pg_db.rb', line 17

def self.setup
  setup_script = File.read(File.join(Dir.pwd, 'db/setup.sql'))
  execute(setup_script)
end