Sha256: 6229ba0ad17d6f22a52b8ab9b1bd37a0dbb5cd2a5172e58cadc2d474dcfaa0b7

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

require 'flipper/adapters/decorator'

module Flipper
  module Adapters
    class Memoizable < Decorator
      FeaturesKey = :flipper_features

      # Internal
      def self.cache
        Thread.current[:flipper_memoize_cache] ||= {}
      end

      # Internal
      def self.memoizing?
        !!Thread.current[:flipper_memoize]
      end

      # Internal
      def self.memoize=(value)
        cache.clear
        Thread.current[:flipper_memoize] = value
      end

      # Public
      def initialize(adapter)
        super(adapter)
      end

      # Public
      def get(feature)
        if memoizing?
          cache.fetch(feature) { cache[feature] = super }
        else
          super
        end
      end

      # Public
      def enable(feature, gate, thing)
        result = super
        cache.delete(feature) if memoizing?
        result
      end

      # Public
      def disable(feature, gate, thing)
        result = super
        cache.delete(feature) if memoizing?
        result
      end

      # Public
      def features
        if memoizing?
          cache.fetch(FeaturesKey) {
            cache[FeaturesKey] = super
          }
        else
          super
        end
      end

      # Public
      def add(feature)
        result = super
        cache.delete(FeaturesKey) if memoizing?
        result
      end

      # Internal
      def cache
        self.class.cache
      end

      # Internal: Turns local caching on/off.
      #
      # value - The Boolean that decides if local caching is on.
      def memoize=(value)
        self.class.memoize = value
      end

      # Internal: Returns true for using local cache, false for not.
      def memoizing?
        self.class.memoizing?
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flipper-0.5.0 lib/flipper/adapters/memoizable.rb