Skip to content

Commit 372025d

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 372025d

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

lib/classifier-reborn/backends/bayes_redis_backend.rb

+5-2
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@
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
10+
# a new connection for you with the same arguments that the
11+
# {redis gem}[https://github.com/redis/redis-rb] accepts
1012
# E.g.,
1113
# b = ClassifierReborn::BayesRedisBackend.new
1214
# b = ClassifierReborn::BayesRedisBackend.new host: "10.0.1.1", port: 6380, db: 2
1315
# b = ClassifierReborn::BayesRedisBackend.new url: "redis://:[email protected]:6380/2"
1416
#
1517
# Options available are:
18+
# redis_conn: an existing redis connection
1619
# url: lambda { ENV["REDIS_URL"] }
1720
# scheme: "redis"
1821
# host: "127.0.0.1"
@@ -33,7 +36,7 @@ def initialize(options = {})
3336
raise NoRedisError
3437
end
3538

36-
@redis = Redis.new(options)
39+
@redis = options.fetch(:redis_conn, Redis.new(options))
3740
@redis.setnx(:total_words, 0)
3841
@redis.setnx(:total_trainings, 0)
3942
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
begin
9+
require 'redis'
10+
rescue LoadError
11+
raise NoRedisError
12+
end
13+
14+
redis = Redis.new
15+
@backend = ClassifierReborn::BayesRedisBackend.new(redis_conn: redis)
16+
redis.config(:set, 'save', '')
17+
rescue Redis::CannotConnectError => e
18+
skip(e)
19+
end
20+
21+
def teardown
22+
@backend.reset if defined? @backend
23+
end
24+
end

0 commit comments

Comments
 (0)