Skip to content

Commit

Permalink
[Fix #30] FeatureCaching: cache nils as :NO_SUCH_FEATURE to avoid re-…
Browse files Browse the repository at this point in the history
…reads
  • Loading branch information
James A. Rosen committed Mar 3, 2013
1 parent 02bbd7c commit a97aa63
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lib/arturo/feature_caching.rb
Expand Up @@ -16,6 +16,10 @@ module Arturo
# to use a shared cache like Memcached.
module FeatureCaching

# A marker in the cache to record the fact that the feature with the
# given symbol doesn't exist.
NO_SUCH_FEATURE = :NO_SUCH_FEATURE

def self.extended(base)
class <<base
alias_method_chain :to_feature, :caching
Expand All @@ -37,10 +41,12 @@ def to_feature_with_caching(feature_or_symbol)
feature_cache.write(feature_or_symbol.symbol.to_sym, feature_or_symbol, :expires_in => cache_ttl)
feature_or_symbol
elsif (cached_feature = feature_cache.read(feature_or_symbol.to_sym))
cached_feature
elsif (f = to_feature_without_caching(feature_or_symbol))
feature_cache.write(f.symbol.to_sym, f, :expires_in => cache_ttl)
f
cached_feature == NO_SUCH_FEATURE ? nil : cached_feature
else
symbol = feature_or_symbol.to_sym
feature = to_feature_without_caching(symbol) || NO_SUCH_FEATURE
feature_cache.write(symbol, feature, :expires_in => cache_ttl)
feature
end
end

Expand Down
7 changes: 7 additions & 0 deletions test/dummy_app/test/unit/cache_test.rb
Expand Up @@ -42,6 +42,13 @@ def test_subsequent_loads_within_ttl_hit_cache
Arturo::Feature.to_feature(@feature.symbol)
end

def test_nils_are_cached
Arturo::Feature.expects(:where).once.returns([])
Arturo::Feature.to_feature(:ramen)
Arturo::Feature.to_feature(:ramen)
Arturo::Feature.to_feature(:ramen)
end

def test_works_with_other_cache_backend
Arturo::Feature.feature_cache = StupidCache.new
Arturo::Feature.expects(:where).once.returns([@feature.reload])
Expand Down

0 comments on commit a97aa63

Please sign in to comment.