Skip to content
Browse files
Extend ActiveRecord::Base#cache_key to take an optional list of times…
…tamp attributes of which the highest will be used.
  • Loading branch information
dhh committed Nov 2, 2013
1 parent 6d30219 commit e94e97ca796c0759d8fcb8f946a3bbc60252d329
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
@@ -1,3 +1,13 @@
* Extend ActiveRecord::Base#cache_key to take an optional list of timestamp attributes of which the highest will be used.


# last_reviewed_at will be used, if that's more recent than updated_at, or vice versa
Person.find(5).cache_key(:updated_at, :last_reviewed_at)


* Added ActiveRecord::Base#enum for declaring enum attributes where the values map to integers in the database, but can be queried by name.

@@ -45,10 +45,18 @@ def to_param
# # => "products/new"
# Product.find(5).cache_key # => "products/5" (updated_at not available)
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
def cache_key
# You can also pass a list of named timestamps, and the newest in the list will be
# used to generate the key:
# Person.find(5).cache_key(:updated_at, :last_reviewed_at)
def cache_key(*timestamp_names)
when new_record?
when timestamp_names.any?
timestamps = timestamp_names.collect { |method| send(method) }.compact
when timestamp = max_updated_column_timestamp
timestamp = timestamp.utc.to_s(cache_timestamp_format)
@@ -3,9 +3,10 @@
require 'models/developer'
require 'models/car'
require 'models/bulb'
require 'models/owner'

class IntegrationTest < ActiveRecord::TestCase
fixtures :companies, :developers
fixtures :companies, :developers, :owners

def test_to_param_should_return_string
assert_kind_of String, Client.first.to_param
@@ -81,4 +82,9 @@ def test_cache_key_format_is_precise_enough
assert_not_equal key, dev.cache_key

def test_named_timestamps_for_cache_key
owner = owners(:blackbeard)
assert_equal "owners/#{}-#{owner.happy_at.utc.to_s(:number)}", owner.cache_key(:updated_at, :happy_at)
@@ -2,6 +2,7 @@ blackbeard:
owner_id: 1
name: blackbeard
essay_id: A Modest Proposal
happy_at: '2150-10-10 16:00:00'

owner_id: 2

0 comments on commit e94e97c

Please sign in to comment.