module RedisCacheable

Usage:

class CacheableObject

include RedisCacheable

attr_reader :id, :name

redis_key :id
redis_attrs :id, :name

def initialize(attrs)
  @id = attrs[:id]
  @name = attrs[:name]
end

end

CacheableObject.new(id: 1, name: “object”).cache_to_redis CacheableObject.find_from_redis(1) # => {“id” => 1, “name” => “target”}

Specialized for ActiveRecord

Constants

VERSION

Public Instance Methods

cache_to_redis(expire: nil) click to toggle source
# File lib/redis_cacheable.rb, line 89
def cache_to_redis(expire: nil)
  redis do |conn|
    if expire
      conn.setex(redis_cache_key, expire, MultiJson.dump(redis_cache_data))
    else
      conn.set(redis_cache_key, MultiJson.dump(redis_cache_data))
    end
  end
end
del_from_redis() click to toggle source
# File lib/redis_cacheable.rb, line 99
def del_from_redis
  redis do |conn|
    conn.del(redis_cache_key)
  end
end
expire_redis(sec) click to toggle source
# File lib/redis_cacheable.rb, line 105
def expire_redis(sec)
  redis do |conn|
    conn.expire(redis_cache_key, sec)
  end
end
expireat_redis(unix_time) click to toggle source
# File lib/redis_cacheable.rb, line 111
def expireat_redis(unix_time)
  redis do |conn|
    conn.expireat(redis_cache_key, unix_time)
  end
end
ttl_redis() click to toggle source
# File lib/redis_cacheable.rb, line 117
def ttl_redis
  redis do |conn|
    conn.ttl(redis_cache_key)
  end
end

Private Instance Methods

__redis_cache_attrs__() click to toggle source
# File lib/redis_cacheable.rb, line 148
def __redis_cache_attrs__
  self.class.__redis_cache_attrs__
end
__redis_cache_key__() click to toggle source
# File lib/redis_cacheable.rb, line 144
def __redis_cache_key__
  self.class.__redis_cache_key__
end
redis_cache_data() click to toggle source
# File lib/redis_cacheable.rb, line 133
def redis_cache_data
  case __redis_cache_attrs__
  when Proc
    __redis_cache_attrs__.call(self)
  when Array
    __redis_cache_attrs__.each_with_object({}) do |attr, hash|
      hash[attr] = send(attr)
    end
  end
end
redis_cache_key() click to toggle source
# File lib/redis_cacheable.rb, line 124
def redis_cache_key
  case __redis_cache_key__
  when Proc
    __redis_cache_key__.call(self)
  when Symbol
    send(__redis_cache_key__)
  end
end