Class: Redis::Namespace

Inherits:
Object
  • Object
show all
Defined in:
lib/redis/namespace.rb,
lib/redis/namespace/version.rb

Constant Summary collapse

NAMESPACED_COMMANDS =

The following tables define how input parameters and result values should be modified for the namespace.

COMMANDS is a hash. Each key is the name of a command and each value is a two element array.

The first element in the value array describes how to modify the arguments passed. It can be one of:

nil
  Do nothing.
:first
  Add the namespace to the first argument passed, e.g.
    GET key => GET namespace:key
:all
  Add the namespace to all arguments passed, e.g.
    MGET key1 key2 => MGET namespace:key1 namespace:key2
:exclude_first
  Add the namespace to all arguments but the first, e.g.
:exclude_last
  Add the namespace to all arguments but the last, e.g.
    BLPOP key1 key2 timeout =>
    BLPOP namespace:key1 namespace:key2 timeout
:exclude_options
  Add the namespace to all arguments, except the last argument,
  if the last argument is a hash of options.
    ZUNIONSTORE key1 2 key2 key3 WEIGHTS 2 1 =>
    ZUNIONSTORE namespace:key1 2 namespace:key2 namespace:key3 WEIGHTS 2 1
:alternate
  Add the namespace to every other argument, e.g.
    MSET key1 value1 key2 value2 =>
    MSET namespace:key1 value1 namespace:key2 value2
:sort
  Add namespace to first argument if it is non-nil
  Add namespace to second arg's :by and :store if second arg is a Hash
  Add namespace to each element in second arg's :get if second arg is
    a Hash; forces second arg's :get to be an Array if present.
:eval_style
  Add namespace to each element in keys argument (via options hash or multi-args)
:scan_style
  Add namespace to :match option, or supplies "#{namespace}:*" if not present.

The second element in the value array describes how to modify the return value of the Redis call. It can be one of:

nil
  Do nothing.
:all
  Add the namespace to all elements returned, e.g.
    key1 key2 => namespace:key1 namespace:key2
{
  "append"           => [ :first ],
  "bitcount"         => [ :first ],
  "bitop"            => [ :exclude_first ],
  "blpop"            => [ :exclude_last, :first ],
  "brpop"            => [ :exclude_last, :first ],
  "brpoplpush"       => [ :exclude_last ],
  "debug"            => [ :exclude_first ],
  "decr"             => [ :first ],
  "decrby"           => [ :first ],
  "del"              => [ :all   ],
  "dump"             => [ :first ],
  "exists"           => [ :first ],
  "expire"           => [ :first ],
  "expireat"         => [ :first ],
  "eval"             => [ :eval_style ],
  "evalsha"          => [ :eval_style ],
  "get"              => [ :first ],
  "getbit"           => [ :first ],
  "getrange"         => [ :first ],
  "getset"           => [ :first ],
  "hset"             => [ :first ],
  "hsetnx"           => [ :first ],
  "hget"             => [ :first ],
  "hincrby"          => [ :first ],
  "hincrbyfloat"     => [ :first ],
  "hmget"            => [ :first ],
  "hmset"            => [ :first ],
  "hdel"             => [ :first ],
  "hexists"          => [ :first ],
  "hlen"             => [ :first ],
  "hkeys"            => [ :first ],
  "hscan"            => [ :first ],
  "hscan_each"       => [ :first ],
  "hvals"            => [ :first ],
  "hgetall"          => [ :first ],
  "incr"             => [ :first ],
  "incrby"           => [ :first ],
  "incrbyfloat"      => [ :first ],
  "keys"             => [ :first, :all ],
  "lindex"           => [ :first ],
  "linsert"          => [ :first ],
  "llen"             => [ :first ],
  "lpop"             => [ :first ],
  "lpush"            => [ :first ],
  "lpushx"           => [ :first ],
  "lrange"           => [ :first ],
  "lrem"             => [ :first ],
  "lset"             => [ :first ],
  "ltrim"            => [ :first ],
  "mapped_hmset"     => [ :first ],
  "mapped_hmget"     => [ :first ],
  "mapped_mget"      => [ :all, :all ],
  "mapped_mset"      => [ :all ],
  "mapped_msetnx"    => [ :all ],
  "mget"             => [ :all ],
  "monitor"          => [ :monitor ],
  "move"             => [ :first ],
  "mset"             => [ :alternate ],
  "msetnx"           => [ :alternate ],
  "object"           => [ :exclude_first ],
  "persist"          => [ :first ],
  "pexpire"          => [ :first ],
  "pexpireat"        => [ :first ],
  "pfadd"            => [ :first ],
  "pfcount"          => [ :all ],
  "pfmerge"          => [ :all ],
  "psetex"           => [ :first ],
  "psubscribe"       => [ :all ],
  "pttl"             => [ :first ],
  "publish"          => [ :first ],
  "punsubscribe"     => [ :all ],
  "rename"           => [ :all ],
  "renamenx"         => [ :all ],
  "restore"          => [ :first ],
  "rpop"             => [ :first ],
  "rpoplpush"        => [ :all ],
  "rpush"            => [ :first ],
  "rpushx"           => [ :first ],
  "sadd"             => [ :first ],
  "scard"            => [ :first ],
  "scan"             => [ :scan_style, :second ],
  "scan_each"        => [ :scan_style, :all ],
  "sdiff"            => [ :all ],
  "sdiffstore"       => [ :all ],
  "set"              => [ :first ],
  "setbit"           => [ :first ],
  "setex"            => [ :first ],
  "setnx"            => [ :first ],
  "setrange"         => [ :first ],
  "sinter"           => [ :all ],
  "sinterstore"      => [ :all ],
  "sismember"        => [ :first ],
  "smembers"         => [ :first ],
  "smove"            => [ :exclude_last ],
  "sort"             => [ :sort  ],
  "spop"             => [ :first ],
  "srandmember"      => [ :first ],
  "srem"             => [ :first ],
  "sscan"            => [ :first ],
  "sscan_each"       => [ :first ],
  "strlen"           => [ :first ],
  "subscribe"        => [ :all ],
  "sunion"           => [ :all ],
  "sunionstore"      => [ :all ],
  "ttl"              => [ :first ],
  "type"             => [ :first ],
  "unsubscribe"      => [ :all ],
  "zadd"             => [ :first ],
  "zcard"            => [ :first ],
  "zcount"           => [ :first ],
  "zincrby"          => [ :first ],
  "zinterstore"      => [ :exclude_options ],
  "zrange"           => [ :first ],
  "zrangebyscore"    => [ :first ],
  "zrank"            => [ :first ],
  "zrem"             => [ :first ],
  "zremrangebyrank"  => [ :first ],
  "zremrangebyscore" => [ :first ],
  "zrevrange"        => [ :first ],
  "zrevrangebyscore" => [ :first ],
  "zrevrank"         => [ :first ],
  "zscan"            => [ :first ],
  "zscan_each"       => [ :first ],
  "zscore"           => [ :first ],
  "zunionstore"      => [ :exclude_options ],
  "[]"               => [ :first ],
  "[]="              => [ :first ]
}
TRANSACTION_COMMANDS =
{
  "discard"          => [],
  "exec"             => [],
  "multi"            => [],
  "unwatch"          => [ :all ],
  "watch"            => [ :all ],
}
HELPER_COMMANDS =
{
  "auth"             => [],
  "disconnect!"      => [],
  "echo"             => [],
  "ping"             => [],
  "time"             => [],
}
ADMINISTRATIVE_COMMANDS =
{
  "bgrewriteaof"     => [],
  "bgsave"           => [],
  "config"           => [],
  "dbsize"           => [],
  "flushall"         => [],
  "flushdb"          => [],
  "info"             => [],
  "lastsave"         => [],
  "quit"             => [],
  "randomkey"        => [],
  "save"             => [],
  "script"           => [],
  "select"           => [],
  "shutdown"         => [],
  "slaveof"          => [],
}
DEPRECATED_COMMANDS =
[
  ADMINISTRATIVE_COMMANDS
].compact.reduce(:merge)
COMMANDS =
[
  NAMESPACED_COMMANDS,
  TRANSACTION_COMMANDS,
  HELPER_COMMANDS,
  ADMINISTRATIVE_COMMANDS,
].compact.reduce(:merge)
Enumerator =

Support 1.8.7 by providing a namespaced reference to Enumerable::Enumerator

Enumerable::Enumerator
VERSION =
'1.5.3'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace, options = {}) ⇒ Namespace

Returns a new instance of Namespace.



235
236
237
238
239
240
241
242
243
244
# File 'lib/redis/namespace.rb', line 235

def initialize(namespace, options = {})
  @namespace = namespace
  @redis = options[:redis] || Redis.current
  @warning = !!options.fetch(:warning) do
               !ENV['REDIS_NAMESPACE_QUIET']
             end
  @deprecations = !!options.fetch(:deprecations) do
                    ENV['REDIS_NAMESPACE_DEPRECATIONS']
                  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(command, *args, &block) ⇒ Object



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/redis/namespace.rb', line 304

def method_missing(command, *args, &block)
  normalized_command = command.to_s.downcase

  if ADMINISTRATIVE_COMMANDS.include?(normalized_command)
    # administrative commands usage is deprecated and will be removed in 2.0
    # redis-namespace cannot safely apply a namespace to their effects.
    return super if deprecations?
    if warning?
      warn("Passing '#{normalized_command}' command to redis as is; " +
           "administrative commands cannot be effectively namespaced " +
           "and should be called on the redis connection directly; " +
           "passthrough has been deprecated and will be removed in " +
           "redis-namespace 2.0 (at #{call_site})"
           )
    end
    call_with_namespace(command, *args, &block)
  elsif COMMANDS.include?(normalized_command)
    call_with_namespace(command, *args, &block)
  elsif @redis.respond_to?(normalized_command) && !deprecations?
    # blind passthrough is deprecated and will be removed in 2.0
    # redis-namespace does not know how to handle this command.
    # Passing it to @redis as is, where redis-namespace shows
    # a warning message if @warning is set.
    if warning?
      warn("Passing '#{command}' command to redis as is; blind " +
           "passthrough has been deprecated and will be removed in " +
           "redis-namespace 2.0 (at #{call_site})")
    end
    @redis.send(command, *args, &block)
  else
    super
  end
end

Instance Attribute Details

#namespace(desired_namespace = nil) ⇒ Object



287
288
289
290
291
292
293
294
# File 'lib/redis/namespace.rb', line 287

def namespace(desired_namespace = nil)
  if desired_namespace
    yield Redis::Namespace.new(desired_namespace,
                               :redis => @redis)
  end

  @namespace
end

#redisObject (readonly)

Returns the value of attribute redis.



232
233
234
# File 'lib/redis/namespace.rb', line 232

def redis
  @redis
end

#warningObject

Returns the value of attribute warning.



233
234
235
# File 'lib/redis/namespace.rb', line 233

def warning
  @warning
end

Instance Method Details

#call_with_namespace(command, *args, &block) ⇒ Object



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/redis/namespace.rb', line 358

def call_with_namespace(command, *args, &block)
  handling = COMMANDS[command.to_s.downcase]

  if handling.nil?
    fail("Redis::Namespace does not know how to handle '#{command}'.")
  end

  (before, after) = handling

  # Modify the local *args array in-place, no need to copy it.
  args.map! {|arg| clone_args(arg)}

  # Add the namespace to any parameters that are keys.
  case before
  when :first
    args[0] = add_namespace(args[0]) if args[0]
  when :all
    args = add_namespace(args)
  when :exclude_first
    first = args.shift
    args = add_namespace(args)
    args.unshift(first) if first
  when :exclude_last
    last = args.pop unless args.length == 1
    args = add_namespace(args)
    args.push(last) if last
  when :exclude_options
    if args.last.is_a?(Hash)
      last = args.pop
      args = add_namespace(args)
      args.push(last)
    else
      args = add_namespace(args)
    end
  when :alternate
    args.each_with_index { |a, i| args[i] = add_namespace(a) if i.even? }
  when :sort
    args[0] = add_namespace(args[0]) if args[0]
    if args[1].is_a?(Hash)
      [:by, :store].each do |key|
        args[1][key] = add_namespace(args[1][key]) if args[1][key]
      end

      args[1][:get] = Array(args[1][:get])

      args[1][:get].each_index do |i|
        args[1][:get][i] = add_namespace(args[1][:get][i]) unless args[1][:get][i] == "#"
      end
    end
  when :eval_style
    # redis.eval() and evalsha() can either take the form:
    #
    #   redis.eval(script, [key1, key2], [argv1, argv2])
    #
    # Or:
    #
    #   redis.eval(script, :keys => ['k1', 'k2'], :argv => ['arg1', 'arg2'])
    #
    # This is a tricky + annoying special case, where we only want the `keys`
    # argument to be namespaced.
    if args.last.is_a?(Hash)
      args.last[:keys] = add_namespace(args.last[:keys])
    else
      args[1] = add_namespace(args[1])
    end
  when :scan_style
    options = (args.last.kind_of?(Hash) ? args.pop : {})
    options[:match] = add_namespace(options.fetch(:match, '*'))
    args << options

    if block
      original_block = block
      block = proc { |key| original_block.call rem_namespace(key) }
    end
  end

  # Dispatch the command to Redis and store the result.
  result = @redis.send(command, *args, &block)

  # Don't try to remove namespace from a Redis::Future, you can't.
  return result if result.is_a?(Redis::Future)

  # Remove the namespace from results that are keys.
  case after
  when :all
    result = rem_namespace(result)
  when :first
    result[0] = rem_namespace(result[0]) if result
  when :second
    result[1] = rem_namespace(result[1]) if result
  end

  result
end

#clientObject



254
255
256
# File 'lib/redis/namespace.rb', line 254

def client
  @redis.client
end

#deprecations?Boolean

Returns:

  • (Boolean)


246
247
248
# File 'lib/redis/namespace.rb', line 246

def deprecations?
  @deprecations
end

#eval(*args) ⇒ Object



300
301
302
# File 'lib/redis/namespace.rb', line 300

def eval(*args)
  call_with_namespace(:eval, *args)
end

#execObject



296
297
298
# File 'lib/redis/namespace.rb', line 296

def exec
  call_with_namespace(:exec)
end

#inspectObject



338
339
340
341
# File 'lib/redis/namespace.rb', line 338

def inspect
  "<#{self.class.name} v#{VERSION} with client v#{Redis::VERSION} "\
  "for #{@redis.id}/#{@namespace}>"
end

#keys(query = nil) ⇒ Object



271
272
273
# File 'lib/redis/namespace.rb', line 271

def keys(query = nil)
  call_with_namespace(:keys, query || '*')
end

#multi(&block) ⇒ Object



275
276
277
278
279
280
281
# File 'lib/redis/namespace.rb', line 275

def multi(&block)
  if block_given?
    namespaced_block(:multi, &block)
  else
    call_with_namespace(:multi)
  end
end

#pipelined(&block) ⇒ Object



283
284
285
# File 'lib/redis/namespace.rb', line 283

def pipelined(&block)
  namespaced_block(:pipelined, &block)
end

#respond_to?(command, include_private = false) ⇒ Boolean

emulate Ruby 1.9+ and keep respond_to_missing? logic together.

Returns:

  • (Boolean)


267
268
269
# File 'lib/redis/namespace.rb', line 267

def respond_to?(command, include_private=false)
  super or respond_to_missing?(command, include_private)
end

#respond_to_missing?(command, include_all = false) ⇒ Boolean

Returns:

  • (Boolean)


343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/redis/namespace.rb', line 343

def respond_to_missing?(command, include_all=false)
  normalized_command = command.to_s.downcase

  case
  when DEPRECATED_COMMANDS.include?(normalized_command)
    !deprecations?
  when COMMANDS.include?(normalized_command)
    true
  when !deprecations? && redis.respond_to?(command, include_all)
    true
  else
    defined?(super) && super
  end
end

#self_respond_to?Object



264
# File 'lib/redis/namespace.rb', line 264

alias_method :self_respond_to?, :respond_to?

#type(key) ⇒ Object

Ruby defines a now deprecated type method so we need to override it here since it will never hit method_missing



260
261
262
# File 'lib/redis/namespace.rb', line 260

def type(key)
  call_with_namespace(:type, key)
end

#warning?Boolean

Returns:

  • (Boolean)


250
251
252
# File 'lib/redis/namespace.rb', line 250

def warning?
  @warning
end