Class: HPG::HPGInternal

Inherits:
Object
  • Object
show all
Defined in:
lib/hpg.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHPGInternal

Returns a new instance of HPGInternal.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/hpg.rb', line 10

def initialize
  # set up logger
  if defined?(Rails.logger) && Rails.logger
    @logger = Rails.logger
  else
    @logger = Logging.logger(STDOUT)
    @logger.level = :info
  end

  # parse env var
  url = find_url
  if url
    parse_url(url)
  end
end

Instance Attribute Details

#databaseObject

Returns the value of attribute database.



8
9
10
# File 'lib/hpg.rb', line 8

def database
  @database
end

#hostObject

Returns the value of attribute host.



8
9
10
# File 'lib/hpg.rb', line 8

def host
  @host
end

#loggerObject

Returns the value of attribute logger.



7
8
9
# File 'lib/hpg.rb', line 7

def logger
  @logger
end

#passwordObject

Returns the value of attribute password.



8
9
10
# File 'lib/hpg.rb', line 8

def password
  @password
end

#portObject

Returns the value of attribute port.



8
9
10
# File 'lib/hpg.rb', line 8

def port
  @port
end

#userObject

Returns the value of attribute user.



8
9
10
# File 'lib/hpg.rb', line 8

def user
  @user
end

Instance Method Details

#find_urlObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hpg.rb', line 26

def find_url
  candidates = ENV.keys.select do |k|
    k =~ /^HEROKU_POSTGRESQL_[A-Z_]+?_URL$/
  end

  key = candidates[0]

  case candidates.length
  when 0
    @logger.fatal 'Could not find the Heroku Postgres URL in ENV'
    @logger.info 'Fix: run `heroku addons:add heroku-postgresql`'
    nil
  when 1
    ENV[key]
  else
    key = candidates.first
    @logger.warn "Found multiple Heroku Postgres URLs; using #{key}"
    @logger.info 'Fix: go to Heroku Dashboard -> Your app -> Settings -> Reveal Config Vars, and delete the extra database config variables'
    ENV[key]
  end
end

#parse_url(url) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hpg.rb', line 48

def parse_url(url)
  begin
    uri = URI.parse(url)
  rescue URI::InvalidURIError
    @logger.fatal 'Heroku Postgres URL is invalid (parse error)'
    @logger.info 'Fix: go to Heroku Dashboard -> Your app -> Settings -> Reveal Config Vars, and make sure the URL is a valid URI'
    return
  end

  if uri.scheme == 'postgres'
    @host = uri.host
    @database = uri.path[1..-1]
    @user = uri.user
    @port = uri.port
    @password = uri.password
    @logger.info 'Successfully grabbed the Heroku Postgres configuration'
  else
    @logger.fatal 'Heroku Postgres URL is invalid (wrong URI scheme)'
    @logger.info 'Fix: go to Heroku Dashboard -> Your app -> Settings -> Reveal Config Vars, and make sure the URL starts with postgres://'
  end
end