Skip to content

Instantly share code, notes, and snippets.

@gdotdesign
Created May 11, 2011 06:15
Show Gist options
  • Save gdotdesign/966001 to your computer and use it in GitHub Desktop.
Save gdotdesign/966001 to your computer and use it in GitHub Desktop.
Cahce
class Cache2
def initialize(opts={})
options = {:expiration => 24*60*60}.merge!(opts)
@exp = options[:expiration]
end
def [](index)
if @cache[index].expired? then @cache[index].refresh end
@cache[index].contents
end
def add(index, expires=nil, &block)
@cache = {}
@cache[index] = Item.new expires || @exp, index, &block
end
class Item
attr_accessor :contents
def initialize(expiration, index, &block)
@index = index
@exp = expiration
@refreshBlock = block
end
def refresh
@contents = @refreshBlock.call @index
@modified = Time.now
end
def expired?
if (Time.now <=> (@modified + @exp)) == -1 then false else true end
end
end
end
cache = Cache2.new({:expiration=>2*60})
cache.add(:tweet) do
Twitter.user_timeline("gdotdesign").first
end
cache.add(:timeline, 2*60*60) do
Twitter.user_timeline("gdotdesign")
end
# now you can use it whereever you like
# and it fetches every two minutes
puts cache[:tweet].text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment