class Looksist::RedisService
Attributes
buffer_size[RW]
cache[RW]
client[RW]
Public Class Methods
instance() { |this| ... }
click to toggle source
# File lib/looksist/redis_service.rb, line 9 def instance @this ||= new @this.buffer_size = 50000 yield @this if block_given? @this.cache = SafeLruCache.new(@this.buffer_size) @this end
Public Instance Methods
flush_cache!()
click to toggle source
# File lib/looksist/redis_service.rb, line 28 def flush_cache! @cache.clear end
method_missing(name, *args, &block)
click to toggle source
Calls superclass method
# File lib/looksist/redis_service.rb, line 18 def method_missing(name, *args, &block) if name.to_s.ends_with?('_for') entity = name.to_s.gsub('_for', '') first_arg = args.first first_arg.is_a?(Array) ? find_all(entity, first_arg) : find(entity, first_arg) else super(name, args) end end
Private Instance Methods
cache_op(computed = nil) { || ... }
click to toggle source
# File lib/looksist/redis_service.rb, line 45 def cache_op(computed = nil) if @buffer_size == 0 return computed.call if computed else yield end end
fetch(key, &block)
click to toggle source
# File lib/looksist/redis_service.rb, line 60 def fetch(key, &block) (cache_op(proc { block.call }) { @cache[key] ||= block.call }) end
find(entity, id)
click to toggle source
# File lib/looksist/redis_service.rb, line 53 def find(entity, id) key = redis_key(entity, id) fetch(key) do @client.get(key) end end
find_all(entity, ids)
click to toggle source
# File lib/looksist/redis_service.rb, line 34 def find_all(entity, ids) raise 'Buffer overflow! Increase buffer size' if ids.length > @buffer_size && @buffer_size != 0 keys = ids.collect { |id| redis_key(entity, id) } missed_keys = cache_op(proc { keys.uniq }) { (keys - @cache.keys).uniq } unless missed_keys.empty? response = Hash[*missed_keys.zip(@client.mget *missed_keys).flatten] cache_op { @cache.merge!(response) } end (cache_op(proc { keys.collect {|k| response[k] } }) { @cache.mslice(keys) }) end
redis_key(entity, id)
click to toggle source
# File lib/looksist/redis_service.rb, line 64 def redis_key(entity, id) "#{entity.pluralize}/#{id}" end