Skip to content

Instantly share code, notes, and snippets.

@yoppi yoppi/redis.rb Secret
Created Mar 25, 2013

Embed
What would you like to do?
Redis wrapper module
# config/initializers/redis.rb
module RedisConf
$redises_ = {}
def self.config
YAML.load_file(File.join(Rails.root, "config/redis.yml"))
end
def self.conn(server)
$redises_[server] ||=
begin
redis_conf = self.config[server][Rails.env]
redis = Redis.new(redis_conf)
raise "Game Redis Server[#{redis_conf[:host]/redis_conf[:port]}] is down!" unless redis.ping == "PONG"
redis
end
end
def self.quit(server)
redis = $redises_[server]
redis.try(:quit)
$redises_[server] = nil
end
def self.reset(server)
quit(server)
conn(server)
end
end
# -*- coding: utf-8 -*-
module KVSKey
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
# return model_name:id:field_name
def kvs_key(name, opts={})
klass_name ||= self.name.tableize
define_method(name) do |id_=nil|
id_ ||= begin
if opts[:id]
opts[:id].call(self)
else
self.id
end
end
KVSKey.join_key(klass_name, id_, name, opts[:blank_field])
end
define_singleton_method(name) do |id_=nil|
id_ ||= opts[:id].call(self)
KVSKey.join_key(klass_name, id_, name, opts[:blank_field])
end
end
def kvs_global_key(name, opts={})
klass_name ||= self.name.tableize
define_singleton_method(name) do
KVSKey.join_key(klass_name, nil, name, opts[:blank_field])
end
end
end
def self.join_key(klass_name, id, name, is_blank_field)
r = "#{klass_name}"
r << ":#{id}" if id
r << ":#{name}" unless is_blank_field
r
end
end
module Redisable
def self.included(base)
base.extend ClassMethods
base.send :include, InstanceMethods
base.send :include, KVSKey
end
module ClassMethods
attr_accessor :redis_server
def redis
n = redis_server.presence || :game
RedisConf.conn(n.to_s)
end
end
module InstanceMethods
private
def redis
@redis_ ||= self.class.redis
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.