lib/flipper/adapter.rb in flipper-0.2.1 vs lib/flipper/adapter.rb in flipper-0.3.0

- old
+ new

@@ -1,7 +1,9 @@ module Flipper - # Internal: Adapter wrapper that wraps vanilla adapter instances with local caching. + # Internal: Adapter wrapper that wraps vanilla adapter instances. Adds things + # like local caching and convenience methods for adding/reading features from + # the adapter. # # So what is this local cache crap? # # The main goal of the local cache is to prevent multiple queries to an # adapter for the same key for a given amount of time (per request, per @@ -15,10 +17,12 @@ # Examples # # To see an example adapter that this would wrap, checkout the [memory # adapter included with flipper](https://github.com/jnunemaker/flipper/blob/master/lib/flipper/adapters/memory.rb). class Adapter + FeaturesKey = 'features' + # Internal: Wraps vanilla adapter instance for use internally in flipper. # # object - Either an instance of Flipper::Adapter or a vanilla adapter instance # # Examples @@ -63,52 +67,60 @@ def using_local_cache? @use_local_cache == true end def read(key) - if using_local_cache? - cache(key) { @adapter.read(key) } - else - @adapter.read(key) - end + perform_read(key) { @adapter.read(key) } end def write(key, value) - @adapter.write(key, value).tap { expire_local_cache(key) } + perform_update(key) { @adapter.write(key, value) } end def delete(key) - @adapter.delete(key).tap { expire_local_cache(key) } + perform_update(key) { @adapter.delete(key) } end def set_members(key) - if using_local_cache? - cache(key) { @adapter.set_members(key) } - else - @adapter.set_members(key) - end + perform_read(key) { @adapter.set_members(key) } end def set_add(key, value) - @adapter.set_add(key, value).tap { expire_local_cache(key) } + perform_update(key) { @adapter.set_add(key, value) } end def set_delete(key, value) - @adapter.set_delete(key, value).tap { expire_local_cache(key) } + perform_update(key) { @adapter.set_delete(key, value) } end def eql?(other) self.class.eql?(other.class) && adapter == other.adapter end alias :== :eql? + def features + set_members(FeaturesKey) + end + + def feature_add(name) + set_add(FeaturesKey, name.to_s) + end + private - def cache(key) - local_cache.fetch(key) { local_cache[key] = yield } + def perform_read(key) + if using_local_cache? + local_cache.fetch(key.to_s) { local_cache[key.to_s] = yield } + else + yield + end end - def expire_local_cache(key) - local_cache.delete(key) if using_local_cache? + def perform_update(key) + result = yield + if using_local_cache? + local_cache.delete(key.to_s) + end + result end end end