Skip to content

Instantly share code, notes, and snippets.

@jgn
Created February 7, 2012 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgn/1759821 to your computer and use it in GitHub Desktop.
Save jgn/1759821 to your computer and use it in GitHub Desktop.
Cached hash
class CachedHash
extend ActiveSupport::Memoizable
def initialize(cache_key)
@cache_key = cache_key
end
def [](key)
fetch[key]
end
def []=(key, value)
value.tap { |value| unfrozen[key] = value; write }
end
def values
fetch.values
end
def clear
{}.tap { |hash| write(hash) }
end
def delete(key)
unfrozen.delete(key).tap { write }
end
def size
fetch.size
end
private
def cache_key
"CACHED_HASH:#{@cache_key}"
end
memoize :cache_key
def write(hash = @hash)
Rails.cache.write(cache_key, hash || {})
end
def fetch
@hash = Rails.cache.fetch(cache_key) { {} }
end
def unfrozen
@hash = fetch.dup
end
end
require 'spec_helper'
describe "a hash backed by a cache" do
subject { CachedHash.new('some_key') }
before(:each) { subject.clear }
context "hash-like methods" do
its(:size) { should == 0 }
it "should be able to store a value under a key" do
subject['foo'] = 'bar'
subject['foo'].should == 'bar'
subject.size.should == 1
end
it "should be able to get all of the values" do
subject['foo'] = 'bar'
subject['boo'] = 'far'
subject.values.should == [ 'bar', 'far' ]
end
it "should be able to clear the hash" do
subject['foo'] = 'bar'
subject.clear.should == {}
subject.size.should == 0
end
it "should be able to delete a key/value pair" do
subject['foo'] = 'bar'
subject.delete('foo').should == 'bar'
subject.size.should == 0
end
it "should be able to return the number of entries" do
subject['foo'] = 'bar'
subject['boo'] = 'far'
subject['The Answer'] = 42
subject.size.should == 3
end
end
context "cache-like features" do
let!(:other_with_same_cache_key) { CachedHash.new('some_key') }
it "should be able to find the same cached information via a different instance" do
subject['foo'] = 'bar'
subject.values.should == other_with_same_cache_key.values
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment