Method: BeerDb.connect

Defined in:
lib/beerdb/models.rb

.connect(config = {}) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/beerdb/models.rb', line 102

def self.connect( config={} )

  if config.empty?
    puts "ENV['DATBASE_URL'] - >#{ENV['DATABASE_URL']}<"

    db = URI.parse( ENV['DATABASE_URL'] || 'sqlite3:///beer.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] # beer.db (Note: cut off leading /, thus 1..-1)
    }
    end
  end

  puts "Connecting to db using settings: "
  pp config
  ActiveRecord::Base.establish_connection( config )
  # ActiveRecord::Base.logger = Logger.new( STDOUT )


  ## if sqlite3 add (use) some pragmas for speedups
  if config[:adapter] == 'sqlite3'
    if config[:database] == ':memory:'
      ## do nothing for in memory database; no pragmas needed
      puts "sqlite3 - no pragmas; using in memory database"
    else
      puts "sqlite3 - pragmas for speedup"
      con = ActiveRecord::Base.connection
      con.execute( 'PRAGMA synchronous=OFF;' )
      con.execute( 'PRAGMA journal_mode=OFF;' )
      con.execute( 'PRAGMA temp_store=MEMORY;' )
    end
  end
end