#cache_key delegates to #object by default

This commit is contained in:
twinturbo 2012-07-11 15:51:25 +02:00
parent b4395f281b
commit e923174a26
2 changed files with 36 additions and 3 deletions

View File

@ -276,7 +276,7 @@ module ActiveModel
def to_json(*args)
if perform_caching?
cache.fetch expand_cache_key([self.class.to_s.underscore, object.cache_key, 'to-json']) do
cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do
super
end
else
@ -305,7 +305,7 @@ module ActiveModel
<<<<<<< HEAD
=======
if perform_caching?
cache.fetch expand_cache_key([self.class.to_s.underscore, object.cache_key, 'serializable-hash']) do
cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'serializable-hash']) do
_serializable_hash
end
else
@ -441,7 +441,17 @@ module ActiveModel
end
def perform_caching?
perform_caching && cache && object.respond_to?(:cache_key)
perform_caching && cache && cache_key
end
# Override this method if you want to create a key based on associations
# Here's an example: your serializer has associations and the scope
#
# def cache_key
# [ object, scope, scope.comments ]
# end
def cache_key
object.try :cache_key
end
def expand_cache_key(*args)

View File

@ -94,4 +94,27 @@ class CachingTest < ActiveModel::TestCase
:skills => ['ruby'],
}.to_json, serializer.cache.read('serializer/Adam/to-json'))
end
def test_can_use_defined_cache_key
serializer = Class.new(ActiveModel::Serializer) do
cache true
attributes :name, :skills
def self.to_s
'serializer'
end
def cache_key
'custom-key'
end
end
serializer.cache = NullStore.new
instance = serializer.new Programmer.new
instance.to_json
assert serializer.cache.read('serializer/custom-key/to-json')
assert serializer.cache.read('serializer/custom-key/serializable-hash')
end
end