From bf82c5c7851839b8dfc44fbbd98deac3b5967286 Mon Sep 17 00:00:00 2001 From: Anthony Ross Date: Fri, 1 Nov 2019 23:02:16 +0000 Subject: [PATCH] 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. --- .../backends/bayes_redis_backend.rb | 7 +++++-- test/backends/backend_redis_injected_test.rb | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 test/backends/backend_redis_injected_test.rb diff --git a/lib/classifier-reborn/backends/bayes_redis_backend.rb b/lib/classifier-reborn/backends/bayes_redis_backend.rb index 758c3f7..729e68d 100644 --- a/lib/classifier-reborn/backends/bayes_redis_backend.rb +++ b/lib/classifier-reborn/backends/bayes_redis_backend.rb @@ -6,13 +6,16 @@ module ClassifierReborn # This class provides Redis as the storage backend for the classifier data structures class BayesRedisBackend - # The class can be created with the same arguments that the redis gem accepts + # 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}[https://github.com/redis/redis-rb] accepts # E.g., # b = ClassifierReborn::BayesRedisBackend.new # b = ClassifierReborn::BayesRedisBackend.new host: "10.0.1.1", port: 6380, db: 2 # b = ClassifierReborn::BayesRedisBackend.new url: "redis://:secret@10.0.1.1:6380/2" # # Options available are: + # redis_conn: an existing redis connection # url: lambda { ENV["REDIS_URL"] } # scheme: "redis" # host: "127.0.0.1" @@ -33,7 +36,7 @@ def initialize(options = {}) raise NoRedisError end - @redis = Redis.new(options) + @redis = options.fetch(:redis_conn, Redis.new(options)) @redis.setnx(:total_words, 0) @redis.setnx(:total_trainings, 0) end diff --git a/test/backends/backend_redis_injected_test.rb b/test/backends/backend_redis_injected_test.rb new file mode 100644 index 0000000..baf945e --- /dev/null +++ b/test/backends/backend_redis_injected_test.rb @@ -0,0 +1,19 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'redis' +require_relative './backend_common_tests' + +class BackendRedisInjectedTest < Minitest::Test + include BackendCommonTests + + def setup + redis = Redis.new + @backend = ClassifierReborn::BayesRedisBackend.new(redis_conn: redis) + redis.config(:set, 'save', '') + rescue Redis::CannotConnectError => e + skip(e) + end + + def teardown + @backend.reset if defined? @backend + end +end