Skip to content

Commit

Permalink
simplified cache method to only take a block. More clear on what it does
Browse files Browse the repository at this point in the history
  • Loading branch information
Karl committed May 18, 2011
1 parent 6378456 commit 095f7db
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
13 changes: 5 additions & 8 deletions lib/simple_redis_cache.rb
Expand Up @@ -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
22 changes: 12 additions & 10 deletions test/simple_redis_cache_test.rb
Expand Up @@ -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


Expand Down

0 comments on commit 095f7db

Please sign in to comment.