Module: RedisClientExtensions

Defined in:
lib/redis-client-extensions.rb,
lib/redis-client-extensions/version.rb

Constant Summary collapse

VERSION =
'0.0.2'

Instance Method Summary collapse

Instance Method Details

#cache_fetch(key, expires_in:, &block) ⇒ Object

Get/set a value cached in a key Values are marshalled to preserve class

key - String key name expires_in: Integer TTL of the key, in seconds block - Proc to compute the value to be cached on miss

Returns cached value or result of evaluating <block>



73
74
75
76
77
78
79
80
81
82
# File 'lib/redis-client-extensions.rb', line 73

def cache_fetch(key, expires_in:, &block)
  if ret = mload(key)
    ret
  else
    val = block.call
    mdump(key, val)
    expire(key, expires_in)
    val
  end
end

#find_keys_in_batches(options = {}) {|keys| ... } ⇒ Object

Wrapper for #scan to iterate over a set of keys matching a pattern

options - Hash of options

:match - String pattern to match against, ex: "mypattern*"
:count - (Optional) Integer hint for number of elements to return
  each iteration

<block> - Proc to handle each batch of keys

Will be invoked with Array[String] of key names

Ex:

$redis.find_keys_in_batches(match: "mypattern*", count: 100) do |keys|
  puts "Got batch of #{keys.count} keys"
  puts "Values for this batch: #{$redis.mget(keys)}"
end

See Redis docs for SCAN.

Returns nothing

Yields:

  • (keys)


43
44
45
46
47
48
49
50
# File 'lib/redis-client-extensions.rb', line 43

def find_keys_in_batches(options={})
  cursor = 0
  while (cursor, keys = scan(cursor, options); cursor.to_i != 0)
    yield keys
  end

  yield keys # Leftovers from final iteration
end

#get_i(key) ⇒ Object

Parse the value stored at ‘key` as an Integer, or return nil if it doesn’t exist

key - String key

Return Integer or nil



59
60
61
62
# File 'lib/redis-client-extensions.rb', line 59

def get_i(key)
  val = get(key)
  val.nil? ? nil : val.to_i
end

#hmultiset(hkey, hash) ⇒ Object

Store a Ruby hash into a redis hash

Examples:

$redis.hmultiset("my-key", { name: "tom", color: "red" })
$redis.hget("my-key", "name") # => "tom"
$redis.hget("my-key", "color") # => "red"

Returns ‘OK’



17
18
19
20
# File 'lib/redis-client-extensions.rb', line 17

def hmultiset(hkey, hash)
  hmset(hkey, *(hash.map { |k, v| [k, v] }.flatten))
  'OK'
end

#mdump(key, val) ⇒ Object

Store a marshalled value at <key>

key - String key val = Any value

Returns ‘OK’



102
103
104
# File 'lib/redis-client-extensions.rb', line 102

def mdump(key, val)
  set(key, Marshal.dump(val))
end

#mload(key) ⇒ Object

Load a Marshalled value stored at <key> Returns nil if key does not exist

Returns class of marshalled value



89
90
91
92
93
# File 'lib/redis-client-extensions.rb', line 89

def mload(key)
  if val = get(key)
    Marshal.load(val)
  end
end