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
#config/redis.yml
default:
  host: localhost
  port: 6379
development:
  db: 0
#  namespace: appname_dev
test:
  db: 1
#  namespace: appname_test
production:
  db: 2
  host: localhost
#  namespace: appname_prod

  1. Update the config/initializer/redis.rb
#config/initializers/redis.rb
REDIS_CONFIG = YAML.load( File.open( 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.new(cnfg)
#$redis_ns = Redis::Namespace.new(cnfg[:namespace], :redis => $redis) if cnfg[:namespace]

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

Much thanks to jlundqvist