mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56:50 +00:00
#cache_key delegates to #object by default
This commit is contained in:
parent
b4395f281b
commit
e923174a26
@ -276,7 +276,7 @@ module ActiveModel
|
|||||||
|
|
||||||
def to_json(*args)
|
def to_json(*args)
|
||||||
if perform_caching?
|
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
|
super
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
@ -305,7 +305,7 @@ module ActiveModel
|
|||||||
<<<<<<< HEAD
|
<<<<<<< HEAD
|
||||||
=======
|
=======
|
||||||
if perform_caching?
|
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
|
_serializable_hash
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
@ -441,7 +441,17 @@ module ActiveModel
|
|||||||
end
|
end
|
||||||
|
|
||||||
def perform_caching?
|
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
|
end
|
||||||
|
|
||||||
def expand_cache_key(*args)
|
def expand_cache_key(*args)
|
||||||
|
|||||||
@ -94,4 +94,27 @@ class CachingTest < ActiveModel::TestCase
|
|||||||
:skills => ['ruby'],
|
:skills => ['ruby'],
|
||||||
}.to_json, serializer.cache.read('serializer/Adam/to-json'))
|
}.to_json, serializer.cache.read('serializer/Adam/to-json'))
|
||||||
end
|
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
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user