[Awesome Ruby Gem] Use redis-namespace gem to namespace Redis keys

redis-namespace

Redis::Namespace provides an interface to a namespaced subset of your redis keyspace (e.g., keys with a common beginning), and requires the GitHub - redis/redis-rb: A Ruby client library for Redis - https://github.com/redis/redis-rb gem.

Installation

You can install it as a gem:

1
$ gem install redis-namespace

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# GitHub - resque/redis-namespace: This gem adds a Redis::Namespace class which can be used to namespace Redis keys.
# https://github.com/resque/redis-namespace
gem 'redis-namespace', '1.8.1'

Then, run bundle install.

1
$ bundle install

Usages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
require 'redis-namespace'
# => true

redis_connection = Redis.new
# => #<Redis client v3.1.0 for redis://127.0.0.1:6379/0>
namespaced_redis = Redis::Namespace.new(:ns, redis: redis_connection)
# => #<Redis::Namespace v1.5.0 with client v3.1.0 for redis://127.0.0.1:6379/0/ns>

namespaced_redis.set('foo', 'bar') # redis_connection.set('ns:foo', 'bar')
# => "OK"

# Redis::Namespace automatically prepended our namespace to the key
# before sending it to our redis client.

namespaced_redis.get('foo')
# => "bar"
redis_connection.get('foo')
# => nil
redis_connection.get('ns:foo')
# => "bar"

namespaced_redis.del('foo')
# => 1
namespaced_redis.get('foo')
# => nil
redis_connection.get('ns:foo')
# => nil

# The prefered way to send an administrative command is on the redis connection itself, which is publicly exposed as Redis::Namespace#redis:
namespaced.redis.flushall()
# => "OK"

References

[1] GitHub - resque/redis-namespace: This gem adds a Redis::Namespace class which can be used to namespace Redis keys. - https://github.com/resque/redis-namespace

[2] redis-namespace | RubyGems.org | your community gem host - https://rubygems.org/gems/redis-namespace

[3] GitHub - redis/redis-rb: A Ruby client library for Redis - https://github.com/redis/redis-rb

[4] Redis - https://redis.io/