./lib/lux/cache/cache.rb in lux-fw-0.1.35 vs ./lib/lux/cache/cache.rb in lux-fw-0.2.1
- old
+ new
@@ -1,23 +1,18 @@
# frozen_string_literal: true
module Lux::Cache
extend self
+ # Lux::Cache.sever = :ram
def server= obj
+ obj = "Lux::Cache::#{obj.to_s.classify}Cache".constantize if obj.class == Symbol
@@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)
+ return nil if (Lux.current.no_cache? rescue false)
@@server.get(key)
end
alias :get :read
def read_multi *args
@@ -34,24 +29,26 @@
def delete key, data=nil
@@server.delete(key)
end
def fetch key, opts={}
- opts = { ttl: opts } unless opts.is_a?(Hash)
- opts = opts.to_opts!(:ttl, :log, :force)
+ opts = { ttl: opts } unless opts.is_a?(Hash)
+ opts = opts.to_opts!(:ttl, :force, :log)
opts.ttl = opts.ttl.to_i if opts.ttl
- opts.log ||= true if opts.log.nil?
- opts.force ||= true if opts.force.nil?
+ opts.log ||= Lux.config(:log_to_stdout) unless opts.log.class == FalseClass
+ opts.force ||= Lux.current.try(:no_cache?) unless opts.force.class == FalseClass
- @@server.delete key if Lux.page && opts.force && Lux.page.no_cache?
+ @@server.delete key if opts.force
Lux.log " Cache.fetch.get #{key} (ttl: #{opts.ttl.or(:nil)})".green if opts.log
data = @@server.fetch key, opts.ttl do
- data = yield
- Lux.log " Cache.fetch.SET #{key} len:#{data.to_s.length}" if opts.log
+ speed = Lux.speed { data = yield }
+
+ Lux.log " Cache.fetch.SET #{key} len:#{data.to_s.length} (#{speed})".red if opts.log
+
data
end
data
end
@@ -61,18 +58,32 @@
get('lux-test') == 9
end
def generate_key *data
keys = []
+
for el in [data].flatten
+ keys.push el.id if el.respond_to?(:id)
+
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)
+ Crypt.sha1(key)
end
+
+ def []= key, value
+ @@server.set key.to_s, value
+ value
+ end
+
+ def [] key
+ @@server.get key.to_s
+ end
+
end