Class: Pluto::Connecter

Inherits:
Object
  • Object
show all
Includes:
LogUtils::Logging
Defined in:
lib/pluto/connecter.rb

Overview

DB Connecter / Connection Manager

lets you establish connection

Instance Method Summary collapse

Constructor Details

#initializeConnecter

Returns a new instance of Connecter.



15
16
17
# File 'lib/pluto/connecter.rb', line 15

def initialize
  # do nothing for now
end

Instance Method Details

#connect(config = {}) ⇒ Object



23
24
25
26
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/pluto/connecter.rb', line 23

def connect( config={} )

  if config.empty?   # use/try DATABASE_URL from environment

    logger.debug "ENV['DATBASE_URL'] - >#{ENV['DATABASE_URL']}<"

    db = URI.parse( ENV['DATABASE_URL'] || 'sqlite3:///pluto.db' )

    if db.scheme == 'postgres'
      config = {
        adapter:  'postgresql',
        host:     db.host,
        port:     db.port,
        username: db.user,
        password: db.password,
        database: db.path[1..-1],
        encoding: 'utf8'
      }
    else   # assume sqlite3
      config = {
        adapter:  db.scheme,       # sqlite3
        database: db.path[1..-1]   # pluto.db (NB: cut off leading /, thus 1..-1)
      }
    end
  end  # if config.nil?

  logger.info 'db settings:'
  logger.info config.pretty_inspect

  ### for dbbrowser and other tools add to ActiveRecord

  if ActiveRecord::Base.configurations.nil?   # todo/check: can this ever happen? remove?
     logger.debug "ActiveRecord configurations nil - set to empty hash"
     ActiveRecord::Base.configurations = {}  # make it an empty hash
  end

  ## todo/fix: remove debug? option - why? why not?
  ##    (just) use logger level eg. logger.debug
  if debug?
    logger.debug 'ar configurations (before):'
    logger.debug ActiveRecord::Base.configurations.pretty_inspect
  end

  # note: for now always use pluto key for config storage
  configs = ActiveRecord::Base.configurations.to_h.reject { |db_config| db_config.env_name == 'pluto' }
  configs['pluto'] = config

  ActiveRecord::Base.configurations = configs

  if debug?
    logger.debug 'ar configurations (after):'
    logger.debug ActiveRecord::Base.configurations.pretty_inspect
  end


  # for debugging - disable for production use
  if debug?
    ActiveRecord::Base.logger = Logger.new( STDOUT )
  end

  ActiveRecord::Base.establish_connection( config )
end

#debug?Boolean

Returns:

  • (Boolean)


19
# File 'lib/pluto/connecter.rb', line 19

def debug?()  Pluto.config.debug?;  end