Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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...
commit e94e97ca796c0759d8fcb8f946a3bbc60252d329 1 parent 6d30219
@dhh dhh authored
View
10 activerecord/CHANGELOG.md
@@ -1,3 +1,13 @@
+* Extend ActiveRecord::Base#cache_key to take an optional list of timestamp attributes of which the highest will be used.
+
+ Example:
+
+ # 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)
+
+ *DHH*
+
+
* Added ActiveRecord::Base#enum for declaring enum attributes where the values map to integers in the database, but can be queried by name.
Example:
View
10 activerecord/lib/active_record/integration.rb
@@ -45,10 +45,18 @@ def to_param
# Product.new.cache_key # => "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)
case
when new_record?
"#{self.class.model_name.cache_key}/new"
+ when timestamp_names.any?
+ timestamps = timestamp_names.collect { |method| send(method) }.compact
+ "#{self.class.model_name.cache_key}/#{id}-#{timestamps.max.utc.to_s(:number)}"
when timestamp = max_updated_column_timestamp
timestamp = timestamp.utc.to_s(cache_timestamp_format)
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
View
8 activerecord/test/cases/integration_test.rb
@@ -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
dev.touch
assert_not_equal key, dev.cache_key
end
+
+ def test_named_timestamps_for_cache_key
+ owner = owners(:blackbeard)
+ assert_equal "owners/#{owner.id}-#{owner.happy_at.utc.to_s(:number)}", owner.cache_key(:updated_at, :happy_at)
+ end
end
View
1  activerecord/test/fixtures/owners.yml
@@ -2,6 +2,7 @@ blackbeard:
owner_id: 1
name: blackbeard
essay_id: A Modest Proposal
+ happy_at: '2150-10-10 16:00:00'
ashley:
owner_id: 2

0 comments on commit e94e97c

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