Skip to content

Instantly share code, notes, and snippets.

@seanknox
Created September 19, 2018 21:24
Show Gist options
  • Save seanknox/aa79e627ebfb282360ad64a938adf665 to your computer and use it in GitHub Desktop.
Save seanknox/aa79e627ebfb282360ad64a938adf665 to your computer and use it in GitHub Desktop.
require 'pry'
class Cache
attr_reader :value
attr_reader :version
attr_reader :versions
# we are storing values as Ruby hash values
def initialize(value = {}, version = 0, versions = [])
@value = value
@version = version
@versions = versions
end
def put(k, v)
# snapshot before we change any data
@versions << Cache.new(@value, @version)
# we assume new values are strings and convert to symbols, for easier get/setting.
new_value = {k.to_sym => v}
@value = @value.merge(new_value)
@version += 1
puts "PUT(##{@version}) #{k} = #{v}"
end
def get(k, version = nil)
if !version.nil? && version < @versions.size - 1
value = @versions[version].value
else
value = @value
end
if value[k.to_sym].nil?
puts "GET #{k} = <NULL>"
else
puts "GET #{k} = #{value[k.to_sym]}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment