DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Redis Init Script For Rails

02.26.2012
| 4998 views |
  • submit to reddit
        You can use the following for a "it just works" approach to using REDIS in rails

First - install redis
brew install redis

Second - create the following.  Note port can be anything you want but they should be unique.  Redis by default runs on 6381 but, using that it risky, if some other app is using that you could get confusing results when keys overlap.

config/redis/development.conf
daemonize yes
port 6390
logfile ./log/redis_development.log
dbfilename ./db/development.rdb

and config/redis/test.conf

daemonize yes
port 6391
logfile ./log/redis_test.log
dbfilename ./db/test.rdb

Third - add this init script
config/init/redis_init.rb
require "redis"
rx = /port.(\d+)/
s = File.read("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
port = rx.match(s)[1]
`redis-server #{::Rails.root}/config/redis/#{::Rails.env}.conf`
res = `ps aux | grep redis-server`
raise "Couldn't start redis" unless res.include?("redis-server") && res.include?("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
REDIS = Redis.new(:port => port)

If you're deploying to Heroku and using redis-to-go use this script
config/init/redis_init.rb

require "redis"

if ::Rails.env == "production"
  uri = URI.parse(ENV["REDISTOGO_URL"])
  REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
else
  rx = /port.(\d+)/
  s = File.read("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
  port = rx.match(s)[1]
  `redis-server #{::Rails.root}/config/redis/#{::Rails.env}.conf`
  res = `ps aux | grep redis-server`
  raise "Couldn't start redis" unless res.include?("redis-server") && res.include?("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
  REDIS = Redis.new(:port => port)
end
</config>

Then - in your app just use the REDIS constant to deal with redis.... example:
REDIS.keys