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') ⇒ Env

Constructor.

Parameters:

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

    The name of the environment variable with the connection URL

Raises:

  • (ArgumentError)


57
58
59
60
61
# File 'lib/pgtk/wire.rb', line 57

def initialize(var = 'DATABASE_URL')
  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?
end

Instance Method Details

#connectionObject

Create a new connection to PostgreSQL server.



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

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])
  ).connection
end