From 640bc92d6d3e060466686f993601a9efde41cbe9 Mon Sep 17 00:00:00 2001 From: fatkodima Date: Sat, 13 Aug 2022 17:29:32 +0300 Subject: [PATCH] Accept Proc as a namespace (#203) Co-authored-by: Lokanadham Co-authored-by: Lokanadham --- CHANGELOG.md | 1 + README.md | 7 +++++++ lib/redis/namespace.rb | 12 ++++++------ spec/redis_spec.rb | 11 +++++++++++ 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7b017c..9dd48c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## x.y.z +- Accept Proc as a namespace (#203) - Fix deprecation warning of Redis.current (#189) - Add support for getex diff --git a/README.md b/README.md index f6473d3..7c11f45 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,13 @@ redis_connection.get('ns:foo') # => nil ``` +Redis::Namespace also supports `Proc` as a namespace and will take the result string as namespace at runtime. + +```ruby +redis_connection = Redis.new +namespaced_redis = Redis::Namespace.new(Proc.new { Tenant.current_tenant }, redis: redis_connection) +``` + Installation ============ diff --git a/lib/redis/namespace.rb b/lib/redis/namespace.rb index 7476950..5aabcaa 100644 --- a/lib/redis/namespace.rb +++ b/lib/redis/namespace.rb @@ -309,7 +309,7 @@ def namespace(desired_namespace = nil) :redis => @redis) end - @namespace + @namespace.respond_to?(:call) ? @namespace.call : @namespace end def full_namespace @@ -317,7 +317,7 @@ def full_namespace end def connection - @redis.connection.tap { |info| info[:namespace] = @namespace } + @redis.connection.tap { |info| info[:namespace] = namespace } end def exec @@ -541,7 +541,7 @@ def namespaced_block(command, &block) end def add_namespace(key) - return key unless key && @namespace + return key unless key && namespace case key when Array @@ -550,12 +550,12 @@ def add_namespace(key) key.keys.each {|k| key[add_namespace(k)] = key.delete(k)} key else - "#{@namespace}:#{key}" + "#{namespace}:#{key}" end end def rem_namespace(key) - return key unless key && @namespace + return key unless key && namespace case key when Array @@ -567,7 +567,7 @@ def rem_namespace(key) key.each { |k| yielder.yield rem_namespace(k) } end else - key.to_s.sub(/\A#{@namespace}:/, '') + key.to_s.sub(/\A#{namespace}:/, '') end end diff --git a/spec/redis_spec.rb b/spec/redis_spec.rb index fdd5745..4470cbe 100644 --- a/spec/redis_spec.rb +++ b/spec/redis_spec.rb @@ -41,6 +41,17 @@ expect(@namespaced.type('counter')).to eq('string') end + it "should work with Proc namespaces" do + namespace = Proc.new { :dynamic_ns } + namespaced = Redis::Namespace.new(namespace, redis: @redis) + + expect(namespaced.get('foo')).to eq(nil) + namespaced.set('foo', 'chris') + expect(namespaced.get('foo')).to eq('chris') + @redis.set('foo', 'bob') + expect(@redis.get('foo')).to eq('bob') + end + context 'when sending capital commands (issue 68)' do it 'should be able to use a namespace' do @namespaced.send('SET', 'fubar', 'quux')