af83

Namespace Redis with ease

Like we have already said we are enthusiastic users of Redis.

In the previous post, we talked about the overuse of namespacing in Redis, and today we'll talk about some good use of namespacing.

I saw more than once something like this:

redis = Redis.new # Get a redis connection
redis.get "users:#{user.id}:friend_ids"

This code grabs from Redis a list of friends for a given user. Actually, it works quite well. But there are some better options, and one of them would be the use of the gem Nest.

The same code would looks like this :

users = Nest.new("users", Redis.new)
users[user.id][:friend_ids].get

In the first line of this example, we can see that Nest provides a namespacing feature.

The second is even more interesting. With redis, generating keys can lead to some mess in your code with lots of interpolations mixing strings and variables.

Generating those keys by the use of chainable namespaces is way nicer and adds an OOP flavor to those keys.

One last thing about Nest, the implementation is just 36 lines long.

Even if namespacing in Redis can be overused, don't forget that there are some nice tools when using it.

blog comments powered by Disqus