Skip to content

Instantly share code, notes, and snippets.

@tal
Last active December 16, 2015 10:38
Show Gist options
  • Select an option

  • Save tal/5421195 to your computer and use it in GitHub Desktop.

Select an option

Save tal/5421195 to your computer and use it in GitHub Desktop.
module RedisHashStore
module ClassMethods
end
module InstanceMethods
def redis_hash_store_key
@redis_hash_store_key ||= "#{self.class.redis_hash_store_key}:#{self.send(self.class.redis_hash_store_uid)}"
end
def hset key, val
REDIS.hset(redis_hash_store_key, key, val)
end
def hincrby key, amt=1
REDIS.hincrby(redis_hash_store_key,key,amt)
end
def hinc key
REDIS.hincrby(redis_hash_store_key,key,1)
end
def hdec key
REDIS.hincrby(redis_hash_store_key,key,-1)
end
def hget key
REDIS.hget(redis_hash_store_key,key)
end
def hdel key
REDIS.hdel(redis_hash_store_key,key)
end
def hgetall
REDIS.hgetall(redis_hash_store_key)
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
receiver.instance_exec do
def store_redis_hash_in key, args={}
@@redis_hash_store_key = key
@@redis_hash_store_uid = args[:uid] || :id
end
def redis_hash_store_key
@@redis_hash_store_key
end
def redis_hash_store_uid
@@redis_hash_store_uid
end
end
end
end
class Foo
include RedisHashStore
store_redis_hash_in 'foo'
end
class FooFoo < Foo; end
class Bar
include RedisHashStore
store_redis_hash_in 'bar'
end
>> Foo.redis_hash_store_key
=> "bar"
>> FooFoo.redis_hash_store_key
=> "bar"
>> Bar.redis_hash_store_key
=> "bar"
>> Foo.redis_hash_store_key
=> "foo"
>> FooFoo.redis_hash_store_key
=> "foo"
>> Bar.redis_hash_store_key
=> "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment