Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add #cache_key to ActiveHash::Base

  • Loading branch information...
commit 06266c9e4032b20d29d66b85e3ab808068e400c0 1 parent a07014a
Tom Stuart tomstuart authored committed

Showing 2 changed files with 35 additions and 0 deletions. Show diff stats Hide diff stats

  1. +11 0 lib/active_hash/base.rb
  2. +24 0 spec/active_hash/base_spec.rb
11 lib/active_hash/base.rb
@@ -307,6 +307,17 @@ def hash
307 307 id.hash
308 308 end
309 309
  310 + def cache_key
  311 + case
  312 + when new_record?
  313 + "#{self.class.model_name.cache_key}/new"
  314 + when timestamp = self[:updated_at]
  315 + "#{self.class.model_name.cache_key}/#{id}-#{timestamp.to_s(:number)}"
  316 + else
  317 + "#{self.class.model_name.cache_key}/#{id}"
  318 + end
  319 + end
  320 +
310 321 def save
311 322 self.class.insert(self)
312 323 true
24 spec/active_hash/base_spec.rb
@@ -626,6 +626,30 @@ class Book < ActiveRecord::Base
626 626
627 627 end
628 628
  629 + describe "#cache_key" do
  630 + it 'should use the class\'s cache_key and id' do
  631 + Country.data = [
  632 + {:id => 1, :name => "foo"}
  633 + ]
  634 +
  635 + Country.first.cache_key.should == 'countries/1'
  636 + end
  637 +
  638 + it 'should use the record\'s updated_at if present' do
  639 + timestamp = Time.now
  640 +
  641 + Country.data = [
  642 + {:id => 1, :name => "foo", :updated_at => timestamp}
  643 + ]
  644 +
  645 + Country.first.cache_key.should == "countries/1-#{timestamp.to_s(:number)}"
  646 + end
  647 +
  648 + it 'should use "new" instead of the id for a new record' do
  649 + Country.new(:id => 1).cache_key.should == 'countries/new'
  650 + end
  651 + end
  652 +
629 653 describe "#save" do
630 654
631 655 before do

0 comments on commit 06266c9

Please sign in to comment.
Something went wrong with that request. Please try again.