Permalink
Browse files

simplified cache method to only take a block. More clear on what it does

  • Loading branch information...
1 parent 6378456 commit 095f7dbfed72f9112a6ea085554800bbf38d76c5 Karl committed May 18, 2011
Showing with 17 additions and 18 deletions.
  1. +5 −8 lib/simple_redis_cache.rb
  2. +12 −10 test/simple_redis_cache_test.rb
View
@@ -10,14 +10,11 @@ def redis
@redis ||= Redis.new
end
- def cache(*args, &block)
- redis[args.first]=(block ? block.call : args.last)
+ def cache(key, opts={}, &block)
+ unless redis.exists(key)
+ redis[key]=block.call
+ redis.expire(key, opts[:ttl]) if opts[:ttl]
+ end
end
- def get(key)
- redis[key]
- end
-
-
-
end
@@ -10,21 +10,23 @@ def setup
redis.flushdb
end
- # Called after every test method runs. Can be used to tear
- # down fixture information.
- def teardown
- # Do nothing
- end
- def test_cache_object
- cache('hello', 'world')
- assert_equal(get('hello'), 'world')
+ def test_expire_block
+ cache('hello', :ttl=>1){ 'world' }
+ sleep(2)
+ assert_nil(redis['hello'])
end
- def test_cache_block
+ def test_cache
cache('hello'){ 'world' }
- assert_equal(get('hello'), 'world')
+ assert_equal(redis['hello'], 'world')
+ end
+
+ def test_block_is_only_executed_once
+ @index = 0
+ 2.times{ cache('hello'){ @index+=1 } }
+ assert_equal(@index, 1)
end

0 comments on commit 095f7db

Please sign in to comment.