Permalink
Browse files

Add #cache_key to ActiveHash::Base

  • Loading branch information...
1 parent a07014a commit 06266c9e4032b20d29d66b85e3ab808068e400c0 @tomstuart tomstuart committed with Aug 7, 2010
Showing with 35 additions and 0 deletions.
  1. +11 −0 lib/active_hash/base.rb
  2. +24 −0 spec/active_hash/base_spec.rb
View
@@ -307,6 +307,17 @@ def hash
id.hash
end
+ def cache_key
+ case
+ when new_record?
+ "#{self.class.model_name.cache_key}/new"
+ when timestamp = self[:updated_at]
+ "#{self.class.model_name.cache_key}/#{id}-#{timestamp.to_s(:number)}"
+ else
+ "#{self.class.model_name.cache_key}/#{id}"
+ end
+ end
+
def save
self.class.insert(self)
true
@@ -626,6 +626,30 @@ class Book < ActiveRecord::Base
end
+ describe "#cache_key" do
+ it 'should use the class\'s cache_key and id' do
+ Country.data = [
+ {:id => 1, :name => "foo"}
+ ]
+
+ Country.first.cache_key.should == 'countries/1'
+ end
+
+ it 'should use the record\'s updated_at if present' do
+ timestamp = Time.now
+
+ Country.data = [
+ {:id => 1, :name => "foo", :updated_at => timestamp}
+ ]
+
+ Country.first.cache_key.should == "countries/1-#{timestamp.to_s(:number)}"
+ end
+
+ it 'should use "new" instead of the id for a new record' do
+ Country.new(:id => 1).cache_key.should == 'countries/new'
+ end
+ end
+
describe "#save" do
before do

0 comments on commit 06266c9

Please sign in to comment.