Created
May 11, 2011 06:15
-
-
Save gdotdesign/966001 to your computer and use it in GitHub Desktop.
Cahce
This file contains 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
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 |
This file contains 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
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