Created
December 24, 2009 15:35
-
-
Save badboy/263235 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby18 | |
# a simple cache class, used in my dzen2 script | |
# usage: | |
# cache = Cache.new(command, time) | |
# where 'command' is program executed with in a shell (using backticks) | |
# and 'time' is the timeout in seconds | |
# to fetch a value: | |
# cache.get | |
# use bang method to ignore cache: | |
# cache.get! | |
# or reset the cache (and optional pass it a new timeout) | |
# cache.reset or cache.reset(10) | |
class Cache | |
def initialize(command, time) | |
@command = command | |
@time = time | |
@last_time = Time.now | |
@value = nil | |
end | |
def get | |
return exec if @value.nil? | |
if time_diff < @time | |
return @value | |
else | |
exec | |
end | |
end | |
def get! | |
exec | |
end | |
def reset(time = nil) | |
@time = time if time | |
@value = nil | |
end | |
def exec | |
@value = `#{@command}` | |
@last_time = Time.now | |
@value | |
end | |
def time_diff | |
(Time.now - @last_time).round | |
end | |
end | |
if $0 == __FILE__ | |
require 'rubygems' | |
require 'test/unit' | |
require 'shoulda' | |
class TestCache < Test::Unit::TestCase | |
context "A cache instance" do | |
setup do | |
@cache = Cache.new('sleep 2;echo foo', 3) | |
end | |
should "fetch value on first get" do | |
t1 = Time.now | |
value = @cache.get | |
t2 = Time.now | |
assert (t2 - t1) >= 2 | |
assert_equal "foo\n", value | |
end | |
should "use cached when in time" do | |
t1 = Time.now | |
value = @cache.get | |
t2 = Time.now | |
value2 = @cache.get | |
t3 = Time.now | |
assert (t2 - t1) >= 2 | |
assert (t3 - t2) <= 1 | |
assert_equal "foo\n", value | |
assert_equal "foo\n", value2 | |
end | |
should "refetch when timed out" do | |
t1 = Time.now | |
value = @cache.get | |
t2 = Time.now | |
sleep 4 | |
t3 = Time.now | |
value2 = @cache.get | |
t4 = Time.now | |
assert (t2 - t1) >= 2 | |
assert (t4 - t3) >= 2 | |
assert_equal "foo\n", value | |
assert_equal "foo\n", value2 | |
end | |
should "refetch when reseted before" do | |
t1 = Time.now | |
value = @cache.get | |
t2 = Time.now | |
@cache.reset | |
t3 = Time.now | |
value2 = @cache.get | |
t4 = Time.now | |
assert (t2 - t1) >= 2 | |
assert (t4 - t3) >= 2 | |
assert_equal "foo\n", value | |
assert_equal "foo\n", value2 | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment