Skip to content

Instantly share code, notes, and snippets.

@squarism
Created November 30, 2011 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squarism/1409491 to your computer and use it in GitHub Desktop.
Save squarism/1409491 to your computer and use it in GitHub Desktop.
ruby cache
# not exactly a pure cache, implements the lookup or expensive operation too
# probably needs to be decoupled
class Cache
def initialize
@cache = {}
end
def cache(name, values = {})
if values = {}
return @cache[name.to_sym]
else
@cache[name.to_sym] ||= values
end
end
def search(name)
if @cache.keys.include?(name.to_sym)
puts "getting name from cache instead of expensive operation"
return @cache[name.to_sym]
else
self.cache(name, Expensive::Search(name))
return @cache[name.to_sym]
end
end
def clear
cache_size = @cache.length
@cache = {}
return cache_size
end
def to_s
"#<Cache:#{self.object_id} Cache Size: #{@cache.length}>"
end
def size
@cache.length
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment