Permalink
Browse files

better Tilt::Cache with specs

  • Loading branch information...
1 parent 83d0dab commit 3435557a97c00c6125c47694221766f8f2a700d1 @rtomayko committed Dec 13, 2009
Showing with 42 additions and 2 deletions.
  1. +7 −2 lib/tilt.rb
  2. +35 −0 test/spec_tilt_cache.rb
View
@@ -167,14 +167,19 @@ def require_template_library(name)
end
end
- # Extremely simple template cache implementation.
+ # Extremely simple template cache implementation. Calling applications
+ # create a Tilt::Cache instance and use #fetch with any set of hashable
+ # arguments (such as those to Tilt.new):
+ # cache = Tilt::Cache.new
+ # cache.fetch(path, line, options) { Tilt.new(path, line, options) }
+ #
+ # Subsequent invocations return the already compiled template object.
class Cache
def initialize
@cache = {}
end
def fetch(*key)
- key = key.map { |part| part.to_s }.join(":")
@cache[key] ||= yield
end
View
@@ -0,0 +1,35 @@
+require 'bacon'
+require 'tilt'
+
+describe Tilt::Cache do
+ before do
+ @cache = Tilt::Cache.new
+ end
+
+ it "caches with single simple argument to #fetch" do
+ template = nil
+ result = @cache.fetch('hello') { template = Tilt::StringTemplate.new {''} }
+ result.object_id.should.equal template.object_id
+ result = @cache.fetch('hello') { fail 'should be cached' }
+ result.object_id.should.equal template.object_id
+ end
+
+ it "caches with multiple complex arguments to #fetch" do
+ template = nil
+ args = ['hello', {:foo => 'bar', :baz => 'bizzle'}]
+ result = @cache.fetch(*args) { template = Tilt::StringTemplate.new {''} }
+ result.object_id.should.equal template.object_id
+ result = @cache.fetch(*args) { fail 'should be cached' }
+ result.object_id.should.equal template.object_id
+ end
+
+ it "clears the cache on #clear" do
+ template, other = nil
+ result = @cache.fetch('hello') { template = Tilt::StringTemplate.new {''} }
+ result.object_id.should.equal template.object_id
+
+ @cache.clear
+ result = @cache.fetch('hello') { other = Tilt::StringTemplate.new {''} }
+ result.object_id.should.equal other.object_id
+ end
+end

0 comments on commit 3435557

Please sign in to comment.