class RedisCollection

Constants

VERSION

Attributes

dump_proc[R]
load_proc[R]
make_key_proc[R]
namespace[R]
redis[R]

Public Class Methods

new(redis, namespace: '', load: -> string { Marshal.load(string) } click to toggle source
# File lib/redis_collection.rb, line 6
def initialize(redis,
  namespace: '',
  load:     -> string { Marshal.load(string) },
  dump:     -> object { Marshal.dump(object) },
  make_key: -> object { object[:id] }
)

  @redis         = redis
  @namespace     = namespace
  @load_proc     = load
  @dump_proc     = dump
  @make_key_proc = make_key

  clear_args
end

Public Instance Methods

sync(collection) click to toggle source

Sync values under a redis namespace with the given collection by

- overwriting existing values
- deleting what's not in collection
# File lib/redis_collection.rb, line 30
def sync(collection)
  clear_args
  updated_namespaced_keys = Set.new

  each_with_key(collection) do |object, key|
    updated_namespaced_keys << "#{namespace}#{key}"
    add_mset "#{namespace}#{key}", dump(object)
  end

  redis.scan_each(match: "#{namespace}*") do |namespaced_key|
    unless updated_namespaced_keys.include?(namespaced_key)
      add_del namespaced_key
    end
  end

  exec!
end

Private Instance Methods

add_del(key) click to toggle source
# File lib/redis_collection.rb, line 76
def add_del(key)
  @del_args << key
end
add_mset(key, value) click to toggle source
# File lib/redis_collection.rb, line 72
def add_mset(key, value)
  @mset_args << key << value
end
clear_args() click to toggle source
# File lib/redis_collection.rb, line 94
def clear_args
  @mset_args = []
  @del_args  = []
end
dump(object) click to toggle source
# File lib/redis_collection.rb, line 84
def dump(object)
  dump_proc.(object)
end
each_with_key(collection) { |object, make_key(object)| ... } click to toggle source
# File lib/redis_collection.rb, line 66
def each_with_key(collection)
  collection.each do |object|
    yield object, make_key(object)
  end
end
exec!() click to toggle source
# File lib/redis_collection.rb, line 50
def exec!
  stats = {
    mset_cnt: @mset_args.size / 2,
    del_cnt:  @del_args.size
  }

  stats[:time] = Benchmark.measure {
    redis.multi do |multi|
      multi.mset(*@mset_args) unless @mset_args.empty?
      multi.del(*@del_args)   unless @del_args.empty?
    end
  }

  stats
end
load(string) click to toggle source
# File lib/redis_collection.rb, line 80
def load(string)
  load_proc.(string)
end
make_key(object) click to toggle source
# File lib/redis_collection.rb, line 88
def make_key(object)
  make_key_proc.(object)
end