Created
February 7, 2012 13:58
-
-
Save jgn/1759819 to your computer and use it in GitHub Desktop.
Cached sequence
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 CachedSequence | |
extend ActiveSupport::Memoizable | |
def initialize(cache_key) | |
@cache_key = cache_key | |
ensure_value | |
end | |
def next | |
Rails.cache.increment(cache_key) | |
end | |
def delete | |
Rails.cache.delete(cache_key) | |
end | |
def reset | |
delete | |
ensure_value | |
end | |
private | |
def ensure_value | |
Rails.cache.fetch(cache_key) { 0 } | |
end | |
def cache_key | |
"CACHED_SEQUENCE:#{@cache_key}" | |
end | |
memoize :cache_key | |
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
require 'spec_helper' | |
describe "a sequence backed by a cache" do | |
subject { CachedSequence.new('test-seq') } | |
before(:each) { subject.reset } | |
it "should have 1 for its initial value" do | |
subject.next.should == 1 | |
end | |
it "should increment by 1 for each requested value" do | |
subject.next | |
subject.next.should == 2 | |
end | |
it "should be possible to delete a sequence" do | |
subject.next | |
subject.delete | |
subject.next.should == nil | |
end | |
it "should be possible to reset a sequence" do | |
subject.next | |
subject.reset | |
subject.next.should == 1 | |
end | |
context "cache-like features" do | |
let!(:other_with_same_cache_key) { CachedSequence.new('test-seq') } | |
it "should be able to find the same cached information via a different instance" do | |
seq = subject.next | |
seq.should == other_with_same_cache_key.next - 1 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment