Sha256: a2716db369f3e0c260bd9558f8538fc0bd35b483175d724d1cde0d348d7e37da

Contents?: true

Size: 1.8 KB

Versions: 2

Compression:

Stored size: 1.8 KB

Contents

# 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

  def read key
    return nil if (Lux.current.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, opts={}
    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   ||= 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 opts.force

    Lux.log " Cache.fetch.get #{key} (ttl: #{opts.ttl.or(:nil)})".green if opts.log

    data = @@server.fetch key, opts.ttl do
      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

  def is_available?
    set('lux-test', 9)
    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('-')
    Crypt.sha1(key)
  end

  def []= key, value
    @@server.set key.to_s, value
    value
  end

  def [] key
    @@server.get key.to_s
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lux-fw-0.2.3 ./lib/lux/cache/cache.rb
lux-fw-0.2.1 ./lib/lux/cache/cache.rb