Sha256: eda366fe356e88c5e1daf13c0eb0710fbb562d1fab50baf2f1ebe9d865aeedc2

Contents?: true

Size: 1.1 KB

Versions: 14

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

module StatsLite
  class Cache
    attr_reader :map

    def initialize
      @map = {}
    end

    class << self
      def fetch(name, proc, expires_s)
        @cache ||= new

        existing = @cache.map[name] if @cache.map.has_key?(name)

        if existing
          if existing.is_a?(Hash) && existing.has_key?(:timestamp)
            if Time.now - existing[:timestamp] > expires_s
              _handle_expires(name, proc)
            else
              existing[:value]
            end
          elsif expires_s > 0
            _handle_expires(name, proc)
          else
            _gey_key(name)
          end
        else
          if expires_s > 0
            _handle_expires(name, proc)
          else
            _set_key(name, proc)
          end
        end
      end

      def _handle_expires(name, proc)
        @cache.map[name] = { timestamp: Time.now, value: proc.call }
        @cache.map[name][:value]
      end

      def _set_key(name, proc)
        @cache.map[name] = proc.call
      end

      def _gey_key(name)
        @cache.map[name]
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
stats_lite-0.8.1 lib/stats_lite/cache.rb
stats_lite-0.8.0 lib/stats_lite/cache.rb
stats_lite-0.7.2 lib/stats_lite/cache.rb
stats_lite-0.7.1 lib/stats_lite/cache.rb
stats_lite-0.7.0 lib/stats_lite/cache.rb
stats_lite-0.6.2 lib/stats_lite/cache.rb
stats_lite-0.6.1 lib/stats_lite/cache.rb
stats_lite-0.6.0 lib/stats_lite/cache.rb
stats_lite-0.5.4 lib/stats_lite/cache.rb
stats_lite-0.5.3 lib/stats_lite/cache.rb
stats_lite-0.5.2 lib/stats_lite/cache.rb
stats_lite-0.5.1 lib/stats_lite/cache.rb
stats_lite-0.5.0 lib/stats_lite/cache.rb
stats_lite-0.1.0 lib/stats_lite/cache.rb