Created
June 1, 2009 03:29
-
-
Save apeckham/121211 to your computer and use it in GitHub Desktop.
MemoryStore that supports expires_in
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
class ExpiringMemoryStore < ActiveSupport::Cache::MemoryStore | |
def read(name, options = nil) | |
out = super(name, options) | |
return if out.nil? | |
return if out.first && out.first < Time.now | |
return out.last | |
end | |
def write(name, value, options = {}) | |
expires_in = options.delete(:expires_in) | |
expires_at = expires_in ? Time.now + expires_in : nil | |
super(name, [expires_at, value], options) | |
end | |
end | |
require File.dirname(__FILE__) + '/unit_test_helper' | |
class ExpiringMemoryStoreTest < Test::Unit::TestCase | |
def test_store | |
start = Time.now | |
Time.stubs(:now).returns(start) | |
store = ExpiringMemoryStore.new | |
store.fetch(:my_key, :expires_in => 10) { 5 } | |
assert_equal 5, store.read(:my_key) | |
Time.stubs(:now).returns(start + 10) | |
assert_equal 5, store.read(:my_key) | |
Time.stubs(:now).returns(start + 11) | |
assert_nil store.read(:my_key) | |
end | |
def test_store_without_expires_in | |
store = ExpiringMemoryStore.new | |
store.fetch(:my_key) { 5 } | |
assert_equal 5, store.read(:my_key) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment