# frozen_string_literal: true module Lux::Cache extend self def server= obj @@server = obj end # cache data in current thread def thread key data = Lux.thread[:cache][key] return data if data Lux.thread[:cache][key] = yield end def read key return nil if (Lux.page.no_cache? rescue false) @@server.get(key) end alias :get :read def read_multi *args @@server.get_multi(*args) end alias :get_multi :read_multi def write key, data, ttl=nil ttl = ttl.to_i if ttl @@server.set(key, data, ttl) end alias :set :write def delete key, data=nil @@server.delete(key) end def fetch key, ttl=nil, log=true ttl = ttl.to_i if ttl @@server.delete key if Lux.page && Lux.page.no_cache? Lux.log " Cache.fetch.get #{key} (ttl: #{ttl.or(:nil)})" if log data = @@server.fetch key, ttl do data = yield Lux.log " Cache.fetch.SET #{key} len:#{data.to_s.length}" if log data end data end def is_available? set('lux-test', 9) get('lux-test') == 9 end def generate_key *data keys = [] for el in [data].flatten if el.respond_to?(:updated_at) keys.push el.updated_at elsif el.respond_to?(:created_at) keys.push el.created_at else keys.push el.to_s end end key = keys.join('-') key.length < 30 ? key : Crypt.md5(key) end end