Howto: Multiple Redis Database for Different Rails Environment

This is a personal note to self. Referenced from a post on Stackoverflow.

One problem I had with running Redis on my Rails app was that on the default configuration, Redis can’t tell if you’re on development or production and hence when doing tests, you may overwrite your development data.

To solve this, lets setup redis to use the correct database for the correct environment:

  1. Add config/redis.yml
  host: localhost
  port: 6379
  db: 0
#  namespace: appname_dev
  db: 1
#  namespace: appname_test
  db: 2
  host: localhost
#  namespace: appname_prod

  1. Update the config/initializer/redis.rb
REDIS_CONFIG = YAML.load( Rails.root.join("config/redis.yml") ) ).symbolize_keys
dflt = REDIS_CONFIG[:default].symbolize_keys
cnfg = dflt.merge(REDIS_CONFIG[Rails.env.to_sym].symbolize_keys) if REDIS_CONFIG[Rails.env.to_sym]

$redis =
#$redis_ns =[:namespace], :redis => $redis) if cnfg[:namespace]

# To clear out the db before each test
$redis.flushdb if Rails.env == "test"

Much thanks to jlundqvist