Class: Pgtk::Wire::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/pgtk/wire/env.rb

Overview

Using ENV variable.

The value of the variable should be in this format:

postgres://user:password@host:port/dbname
Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2019-2026 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(var = 'DATABASE_URL', **opts) ⇒ Env

Constructor.

Parameters:

  • var (String) (defaults to: 'DATABASE_URL')

    The name of the environment variable with the connection URL

  • opts (Hash)

    Extra options forwarded to PG.connect (e.g. sslmode, connect_timeout, keepalives, keepalives_idle, application_name). Explicit kwargs win over options carried in the URL query string on conflict.

Raises:

  • (ArgumentError)


29
30
31
32
33
34
# File 'lib/pgtk/wire/env.rb', line 29

def initialize(var = 'DATABASE_URL', **opts)
  raise(ArgumentError, "The name of the environment variable can't be nil") if var.nil?
  @value = ENV.fetch(var, nil)
  raise(ArgumentError, "The environment variable #{@value.inspect} is not set") if @value.nil?
  @opts = opts
end

Instance Method Details

#connectionObject

Create a new connection to PostgreSQL server.



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pgtk/wire/env.rb', line 37

def connection
  uri = URI(@value)
  Pgtk::Wire::Direct.new(
    host: CGI.unescape(uri.host),
    port: uri.port || 5432,
    dbname: CGI.unescape(uri.path[1..]),
    user: CGI.unescape(uri.userinfo.split(':')[0]),
    password: CGI.unescape(uri.userinfo.split(':')[1]),
    **(uri.query ? URI.decode_www_form(uri.query).to_h.transform_keys(&:to_sym) : {}).merge(@opts)
  ).connection
end