Platinum Partner

Redis Init Script For Rails

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


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

REDIS.keys

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}