module Redis::Helper
redisのヘルパー
Constants
- DEFAULT_UNIQUE_ATTR_NAME
デフォルトの固有キー名
- LOCK_POSTFIX
ロックを取得に利用する接尾辞
- REDIS_KEY_DELIMITER
redisキーの区切り文字
- VERSION
バージョン
Public Class Methods
# File lib/redis/helper.rb, line 44 def self.included(klass) klass.extend ClassMethods end
Public Instance Methods
instance固有のkeyとattr_nameからkeyを生成する (instanceに複数のkeyを設定したい場合やkeyにattr_nameを含めたい場合に使用する) @param [String|Symbol] attr_name キー名 @param [String|Symbol] unique_attr インスタンスの固有キーとして使用するメソッド名 @return [String]
# File lib/redis/helper.rb, line 92 def attr_key(attr_name, unique_attr = nil) self.class.generate_key(unique_key(unique_attr), attr_name) end
instance固有のkeyを生成する (“<Class Name>:<unique key>”) @param [String|Symbol] unique_attr インスタンスの固有キーとして使用するメソッド名 @return [String]
# File lib/redis/helper.rb, line 99 def instance_key(unique_attr = nil) self.class.generate_key(unique_key(unique_attr)) end
特定のkeyをbaseにしたロックをかけてブロック内の処理を実行 @example
lock(attr_key(:foo)) { # some processing }
@param [String] base_key ロックを取得するリソースのkey @yield ロック中に実行する処理のブロック
# File lib/redis/helper.rb, line 132 def lock(base_key, &block) self.class.lock(base_key, &block) end
Redis.currentへのショートカット @return [Redis]
# File lib/redis/helper.rb, line 121 def redis self.class.redis end
引数で指定した時間にexpireするためのttl値を生成 @example
# 2016/10/26 正午にexpireする redis.setex(key, ttl_to(Time.zone.parse("2016-10-26 12:00:00")), value) # 24時間後にexpireする redis.setex(key, ttl_to(1.day.since), value)
@param [Time] to_time expireする時間 @param [Time] from_time 現在時間 @param [Boolean] unsigned_non_zero 計算結果のttlが0の場合1を返す @return [Integer]
# File lib/redis/helper.rb, line 113 def ttl_to(to_time, from_time = Time.current, unsigned_non_zero: true) ttl = (to_time - from_time).to_i return ttl if ttl > 0 unsigned_non_zero ? 1 : ttl end
インスタンス固有のキーを取得 @param [String|Symbol] unique_attr インスタンスの固有キーとして使用するメソッド名
# File lib/redis/helper.rb, line 138 def unique_key(unique_attr = nil) attr_name = unique_attr.presence || DEFAULT_UNIQUE_ATTR_NAME if (unique_key = self.public_send(attr_name)).blank? raise UnknownUniqueValue, "unique keyとして指定された値(#{attr_name})が取得できません" end unique_key end