redis snippets

How to install and use Redis with Ruby

Tagged ruby, key-value, database, cat, redis  Languages ruby

Redis and redis-rb example:

git clone git://github.com/ezmobius/redis-rb.git
cd redis-rb/
rake redis:install
rake dtach:install
rake redis:start &
rake install

cat <<EOF >>test.rb
require 'rubygems'
require 'redis'

r = Redis.new

r.delete('foo')

p'set foo to "bar"'
r['foo'] = 'bar'

p 'value of foo'
p r['foo']
EOF

ruby test.rb

If Redis is not started Ruby will exit at Redis.new for some reason without saying anything.

Simple Redis cache utility for Ruby

Tagged cache, redis, sinatra  Languages ruby

Use it at your own risk with e.g. Sinatra:

require 'redis'

module Cache
  mattr_accessor :redis
  class << self
    def get(key)
      Cache.redis.get(key)
    end

    def set(key, value, ttl=nil)
      if ttl
        Cache.redis.setex(key, ttl, value)
      else
        Cache.redis.set(key, value)
      end
    end

    def fetch(key)
      value = get(key)
      value = yield if block_given? && value.nil?
      value
    end

    def establish_connection
      redis_config = YAML.load_file(File.join(Dir.pwd, 'config', 'redis.yml'))
      Cache.redis.client.disconnect if Cache.redis
      Cache.redis = Redis.new(:host => redis_config["host"], :port => redis_config["port"])
    end
  end
end