Class: Pgtk::Wire::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/pgtk/wire.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)


64
65
66
67
68
69
# File 'lib/pgtk/wire.rb', line 64

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.



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/pgtk/wire.rb', line 72

def connection
  uri = URI(@value)
  extras = uri.query ? URI.decode_www_form(uri.query).to_h.transform_keys(&:to_sym) : {}
  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]),
    **extras.merge(@opts)
  ).connection
end