diff --git a/lib/simple_redis_cache.rb b/lib/simple_redis_cache.rb index 5ecdd23..547532b 100644 --- a/lib/simple_redis_cache.rb +++ b/lib/simple_redis_cache.rb @@ -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 diff --git a/test/simple_redis_cache_test.rb b/test/simple_redis_cache_test.rb index 9a2905a..70a1f29 100755 --- a/test/simple_redis_cache_test.rb +++ b/test/simple_redis_cache_test.rb @@ -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