Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Namespace Redis with ease

Parent Feed: 

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web