Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/pg/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,15 @@ def self.connect_hash_to_string( hash )
# * URI string
# * URI object
# * positional arguments
#
# If an option Hash is used, :password can be a Proc or lambda that returns a
# string, so as to support dynamic passwords.
#
# The method adds the option "fallback_application_name" if it isn't already set.
# It returns a connection string with "key=value" pairs.
def self.parse_connect_args( *args )
hash_arg = args.last.is_a?( Hash ) ? args.pop.transform_keys(&:to_sym) : {}
hash_arg[:password] = hash_arg[:password].call if hash_arg[:password].respond_to?(:call)
iopts = {}

if args.length == 1
Expand Down
22 changes: 22 additions & 0 deletions spec/pg/connection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,28 @@
PG::Connection.class_eval("PROGRAM_NAME=PG.make_shareable(#{old_script_name.inspect})")
end
end

it "accepts a lambda as the :password key of a Hash parameter" do
optstring = described_class.parse_connect_args(
:dbname => 'db01',
:password => lambda { 'password_via_lambda' }
)

expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)dbname='db01'/ )
expect( optstring ).to match( /(^|\s)password='password_via_lambda'/ )
end

it "accepts a Proc as the :password key of a Hash parameter" do
optstring = described_class.parse_connect_args(
:dbname => 'db01',
:password => Proc.new { 'password_via_Proc' }
)

expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)dbname='db01'/ )
expect( optstring ).to match( /(^|\s)password='password_via_Proc'/ )
end
end

it "connects successfully with connection string" do
Expand Down
Loading