Skip to content

Instantly share code, notes, and snippets.

@nickhoffman
Created April 29, 2016 19:03
Show Gist options
  • Save nickhoffman/3d8fc9a5a1f691d867c807ef63c1e642 to your computer and use it in GitHub Desktop.
Save nickhoffman/3d8fc9a5a1f691d867c807ef63c1e642 to your computer and use it in GitHub Desktop.
Code Kata: Cache
class Cache
end
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