Skip to content

Commit 3a26c63

Browse files
author
Anthony Ross
committed
Allow Redis Connection to be Injected
See issue #188 for details. Prior to this change, pooled redis connections were hard to share across. Now you can inject your own redis connection into the intiailizer via the `redis_conn` parameter.
1 parent 0d5564a commit 3a26c63

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

lib/classifier-reborn/backends/bayes_redis_backend.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@
66
module ClassifierReborn
77
# This class provides Redis as the storage backend for the classifier data structures
88
class BayesRedisBackend
9-
# The class can be created with the same arguments that the redis gem accepts
9+
# The class can be given an existing redis connection, or it can create a new connection for you with the same arguments that the redis gem accepts
1010
# E.g.,
1111
# b = ClassifierReborn::BayesRedisBackend.new
1212
# b = ClassifierReborn::BayesRedisBackend.new host: "10.0.1.1", port: 6380, db: 2
1313
# b = ClassifierReborn::BayesRedisBackend.new url: "redis://:secret@10.0.1.1:6380/2"
1414
#
1515
# Options available are:
16+
# redis_conn: an existing redis connection (useful if you are using a pool of connections)
1617
# url: lambda { ENV["REDIS_URL"] }
1718
# scheme: "redis"
1819
# host: "127.0.0.1"
@@ -33,7 +34,7 @@ def initialize(options = {})
3334
raise NoRedisError
3435
end
3536

36-
@redis = Redis.new(options)
37+
@redis = options.fetch(:redis_conn, Redis.new(options))
3738
@redis.setnx(:total_words, 0)
3839
@redis.setnx(:total_trainings, 0)
3940
end
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
require File.dirname(__FILE__) + '/../test_helper'
2+
require_relative './backend_common_tests'
3+
4+
class BackendRedisInjectedTest < Minitest::Test
5+
include BackendCommonTests
6+
7+
def setup
8+
redis = Redis.new
9+
@backend = ClassifierReborn::BayesRedisBackend.new(redis_conn: redis)
10+
redis.config(:set, 'save', '')
11+
rescue Redis::CannotConnectError => e
12+
skip(e)
13+
end
14+
15+
def teardown
16+
@backend.reset if defined? @backend
17+
end
18+
end

0 commit comments

Comments
 (0)