Permalink
Browse files

Add FeatureCaching#warm_cache!

  • Loading branch information...
1 parent 9306921 commit 8c12a9f5e0306d68fc09d419e990a4c1e0a50d5e James A. Rosen committed May 16, 2013
Showing with 38 additions and 3 deletions.
  1. +19 −3 README.md
  2. +10 −0 lib/arturo/feature_caching.rb
  3. +9 −0 test/dummy_app/test/unit/cache_test.rb
View
22 README.md
@@ -266,11 +266,27 @@ Both check whether the `foo` feature exists and is enabled for `recipient`.
#### Caching
-**Note**: Arturo does not yet have caching support. Be very careful when
+**Note**: Arturo has support for caching `Feature` lookups, but doesn't yet
+integrate with Rails's caching. This means you should be very careful when
caching actions or pages that involve feature detection as you will get
strange behavior when a user who has access to a feature requests a page
-just after one who does not (and vice versa). The following is the
-**intended** support for caching.
+just after one who does not (and vice versa).
+
+To enable caching `Feature` lookups, mix `Arturo::FeatureCaching` into
+`Arturo::Feature` and set the `cache_ttl`. This is best done in an
+initializer:
+
+ Arturo::Feature.extend(Arturo::FeatureCaching)
+ Arturo::Feature.cache_ttl = 10.minutes
+
+You can also warm the cache on startup:
+
+ Arturo::Feature.warm_cache!
+
+This will pre-fetch all `Feature`s and put them in the cache.
+
+
+The following is the **intended** support for integration with view caching:
Both the `require_feature` before filter and the `if_feature_enabled` block
evaluation automatically append a string based on the feature's
View
10 lib/arturo/feature_caching.rb
@@ -48,6 +48,16 @@ def to_feature_with_caching(feature_or_symbol)
end
end
+ # Warms the cache by fetching all `Feature`s and caching them.
+ # This is perfect for use in an initializer.
+ def warm_cache!
+ raise "Cannot warm Feature Cache; caching is disabled" unless caches_features?
+
+ all.each do |feature|
+ feature_cache.write(feature.symbol.to_sym, feature, :expires_in => cache_ttl)
+ end
+ end
+
protected
# Quack like a Rails cache.
View
9 test/dummy_app/test/unit/cache_test.rb
@@ -81,4 +81,13 @@ def test_ttl_expiry
Arturo::Feature.to_feature(@feature.symbol)
end
+ def test_warm_cache
+ second_feature = create(:feature)
+ Arturo::Feature.warm_cache!
+
+ Arturo::Feature.expects(:where).never
+ assert_equal @feature, Arturo::Feature.to_feature(@feature.symbol)
+ assert_equal second_feature, Arturo::Feature.to_feature(second_feature.symbol)
+ end
+
end

0 comments on commit 8c12a9f

Please sign in to comment.