-
-
Save nickhoffman/3d8fc9a5a1f691d867c807ef63c1e642 to your computer and use it in GitHub Desktop.
Code Kata: Cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cache | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './cache.rb' | |
cache = Cache.new | |
tests = [ | |
Proc.new do |cache| | |
cache.get(:foo).nil? | |
end, | |
Proc.new do |cache| | |
cache.set(:foo, 'FOO') == 'FOO' | |
end, | |
Proc.new do |cache| | |
cache.set(:foo, 'FOO') | |
cache.get(:foo) == 'FOO' | |
end, | |
Proc.new do |cache| | |
cache.set(:foo, 'FOO') | |
cache.delete(:foo) == 'FOO' | |
end, | |
Proc.new do |cache| | |
cache.set(:foo, 'FOO') | |
cache.delete(:foo) | |
cache.get(:foo).nil? | |
end, | |
Proc.new do |cache| | |
num_calls = 0 | |
calculation = -> { num_calls += 1 } | |
cache.fetch(:foo, &calculation) == 1 && cache.fetch(:foo, &calculation) == 1 | |
end, | |
Proc.new do |cache| | |
now = Time.now | |
expires_at = now + 100 | |
cache.set(:foo, 'FOO', expires_at: expires_at) | |
cache.get(:foo) == 'FOO' | |
end, | |
Proc.new do |cache| | |
now = Time.now | |
expires_at = now - 1 | |
cache.set(:foo, 'FOO', expires_at: expires_at) | |
cache.get(:foo).nil? | |
end, | |
Proc.new do |cache| | |
now = Time.now | |
expires_at = now + 1 | |
cache.set(:foo, 'FOO', expires_at: expires_at) | |
sleep(1.2) | |
cache.get(:foo).nil? | |
end, | |
] | |
tests.each_with_index do |test, i| | |
print "Test #{i}: " | |
begin | |
if test.call(cache) | |
puts 'success' | |
else | |
puts 'fail' | |
end | |
rescue StandardError => exception | |
puts "error: #{exception.inspect}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment