Created
November 30, 2011 15:32
-
-
Save squarism/1409491 to your computer and use it in GitHub Desktop.
ruby 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
# 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