From 223233ac9786eeeefe2de6e2e8cd312a597f8045 Mon Sep 17 00:00:00 2001 From: Stefan Wille Date: Tue, 2 Feb 2016 11:47:16 +0100 Subject: [PATCH] When connecting, allow extra parameter 'password'. Fixes #10 --- spec/password_spec.cr | 12 ++++++++++++ src/redis.cr | 10 ++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 spec/password_spec.cr diff --git a/spec/password_spec.cr b/spec/password_spec.cr new file mode 100644 index 0000000..ed4a1a9 --- /dev/null +++ b/spec/password_spec.cr @@ -0,0 +1,12 @@ +require "./spec_helper" +# This spec is commented out because it requires a Redis instance +# with password authentication. +# +# describe Redis do +# describe ".new with password" do +# it "connects with a password" do +# redis = Redis.new(host: "localhost", port: 6379, password: "foobared") +# redis.set("foo", "bar") +# end +# end +# end diff --git a/src/redis.cr b/src/redis.cr index 8364204..7cde94c 100644 --- a/src/redis.cr +++ b/src/redis.cr @@ -49,6 +49,7 @@ class Redis # * host - the host to connect to # * port - the port to connect to # * unixsocket - instead of using TCP, you can connect to Redis via a Unix domain socket by passing its path here (e.g. "/tmp/redis.sock") + # * password - the password for authentication against the server. This is a convenience which saves you the extra call to the Redis `auth` command. # # Example: # @@ -71,9 +72,13 @@ class Redis # redis = Redis.new(unixsocket: "/tmp/redis.sock") # ... # ``` - def initialize(host = "localhost", port = 6379, unixsocket = nil) + def initialize(host = "localhost", port = 6379, unixsocket = nil, password = nil) @connection = Connection.new(host, port, unixsocket) @strategy = Redis::Strategy::SingleStatement.new(@connection) + + if password + auth(password) + end end # Opens a Redis connection, yields the given block with a Redis object and closes the connection. @@ -82,6 +87,7 @@ class Redis # * host - the host to connect to # * port - the port to connect to # * unixsocket - instead of using TCP, you can connect to Redis via a Unix domain socket by passing its path here (e.g. "/tmp/redis.sock") + # * password - the password for authentication against the server. This is a convenience which saves you the extra call to the Redis `auth` command. # # Example: # @@ -90,7 +96,7 @@ class Redis # redis.incr("counter") # end # ``` - def self.open(host = "localhost", port = 6379, unixsocket = nil) + def self.open(host = "localhost", port = 6379, unixsocket = nil, password = nil) redis = Redis.new(host, port, unixsocket) begin yield(redis)