Permalink
Browse files

Thread safety for memoizable.

  • Loading branch information...
jnunemaker committed Feb 15, 2013
1 parent e8eec56 commit a1c38044e423ccb2eaae04925e4e2e078871007e
@@ -5,32 +5,31 @@ module Adapters
class Memoizable < Decorator
FeaturesKey = :flipper_features
- # Private: The cache of memoized adapter operations and results.
- attr_reader :cache
+ # Internal
+ def self.cache
+ Thread.current[:flipper_memoize_cache] ||= {}
+ end
- # Public
- def initialize(adapter, cache = nil)
- super(adapter)
- @cache = cache || {}
+ # Internal
+ def self.memoizing?
+ !!Thread.current[:flipper_memoize]
end
- # Public: Turns local caching on/off.
- #
- # value - The Boolean that decides if local caching is on.
- def memoize=(value)
+ # Internal
+ def self.memoize=(value)
cache.clear
- @memoize = value
+ Thread.current[:flipper_memoize] = value
end
- # Public: Returns true for using local cache, false for not.
- def memoizing?
- !!@memoize
+ # Public
+ def initialize(adapter)
+ super(adapter)
end
# Public
def get(feature)
if memoizing?
- @cache.fetch(feature) { @cache[feature] = super }
+ cache.fetch(feature) { cache[feature] = super }
else
super
end
@@ -39,22 +38,22 @@ def get(feature)
# Public
def enable(feature, gate, thing)
result = super
- @cache.delete(feature) if memoizing?
+ cache.delete(feature) if memoizing?
result
end
# Public
def disable(feature, gate, thing)
result = super
- @cache.delete(feature) if memoizing?
+ cache.delete(feature) if memoizing?
result
end
# Public
def features
if memoizing?
- @cache.fetch(FeaturesKey) {
- @cache[FeaturesKey] = super
+ cache.fetch(FeaturesKey) {
+ cache[FeaturesKey] = super
}
else
super
@@ -64,9 +63,26 @@ def features
# Public
def add(feature)
result = super
- @cache.delete(FeaturesKey) if memoizing?
+ 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
@@ -6,11 +6,15 @@
describe Flipper::Adapters::Memoizable do
let(:features_key) { described_class::FeaturesKey }
- let(:cache) { {} }
let(:adapter) { Flipper::Adapters::Memory.new }
let(:flipper) { Flipper.new(adapter) }
+ let(:cache) { Thread.current[:flipper_memoize_cache] }
- subject { described_class.new(adapter, cache) }
+ after do
+ described_class.memoize = nil
+ end
+
+ subject { described_class.new(adapter) }
it_should_behave_like 'a flipper adapter'
@@ -30,6 +30,10 @@
end.to_app
}
+ after do
+ flipper.adapter.memoize = nil
+ end
+
it "delegates" do
called = false
app = lambda { |env|

0 comments on commit a1c3804

Please sign in to comment.