From a72fec226c4c67b2233aab010e14a6b11691c2e0 Mon Sep 17 00:00:00 2001 From: Geremia Taglialatela Date: Thu, 21 Nov 2024 11:04:05 +0100 Subject: [PATCH] Prioritize hash in connection parameter detection Allow to detect hashes responding to `#call`, like `ActiveSupport::OrderedOptions` This will enable out of the box compatibility with `Rails.application.config_for` method and should not break existing use cases, because `ConnectionPool` and `RedisClient` do not inherit from `Hash` Close #152 --- lib/redlock/client.rb | 13 ++++--------- spec/client_spec.rb | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/redlock/client.rb b/lib/redlock/client.rb index 24be410..fe3c710 100644 --- a/lib/redlock/client.rb +++ b/lib/redlock/client.rb @@ -160,17 +160,12 @@ class RedisInstance def initialize(connection) @monitor = Monitor.new - if connection.respond_to?(:call) - @redis = connection - else - if connection.respond_to?(:client) - @redis = connection - elsif connection.respond_to?(:key?) - @redis = initialize_client(connection) + @redis = + if connection.is_a?(Hash) + initialize_client(connection) else - @redis = connection + connection end - end end def initialize_client(options) diff --git a/spec/client_spec.rb b/spec/client_spec.rb index d46f6e5..13fabf0 100644 --- a/spec/client_spec.rb +++ b/spec/client_spec.rb @@ -65,6 +65,20 @@ lock_manager.unlock(lock_info) end + it 'accepts hashes responding to call like ActiveSupport::OrderedOptions' do + callable_hash = Class.new(Hash) do + def call; end + end + + config = callable_hash.new.merge(url: "redis://#{redis1_host}:#{redis1_port}") + redlock = Redlock::Client.new([config]) + + lock_info = redlock.lock(resource_key, ttl) + expect(lock_info).to be_a(Hash) + expect(resource_key).to_not be_lockable(lock_manager, ttl) + redlock.unlock(lock_info) + end + it 'does not load scripts' do redis_client.call('SCRIPT', 'FLUSH')