Skip to content

Commit

Permalink
Use ActiveSupport::Cache.expand_cache_key for cache key expansions
Browse files Browse the repository at this point in the history
  • Loading branch information
markiz committed Aug 12, 2016
1 parent 9217bc2 commit 2811e9e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/active_model/serializer/caching.rb
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,11 @@ def cache_key(adapter_instance)
parts << object_cache_key
parts << adapter_instance.cache_key
parts << serializer_class._cache_digest unless serializer_class._skip_digest?
@cache_key = parts.join('/')
@cache_key = expand_cache_key(parts)
end

def expand_cache_key(parts)
ActiveSupport::Cache.expand_cache_key(parts)
end

# Use object's cache_key if available, else derive a key from the object
Expand Down
36 changes: 36 additions & 0 deletions test/cache_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@

module ActiveModelSerializers
class CacheTest < ActiveSupport::TestCase
class AuthorWithCustomCacheKey < Author
class DerivedCacheKey
def initialize(object, method)
@object = object
@method = method
end

def cache_key
@object.__send__(@method)
end
end

def cache_key
[
DerivedCacheKey.new(self, :name),
DerivedCacheKey.new(self, :id)
]
end
end

class UncachedAuthor < Author
# To confirm cache_key is set using updated_at and cache_key option passed to cache
undef_method :cache_key
Expand Down Expand Up @@ -106,6 +126,22 @@ def test_cache_key_interpolation_with_updated_at_when_cache_key_is_not_defined_o
assert_equal(uncached_author_serializer.attributes.to_json, cache_store.fetch(key).to_json)
end

def test_cache_key_with_non_primitive_values
author = AuthorWithCustomCacheKey.new(id: 10, name: "hello")
same_author = AuthorWithCustomCacheKey.new(id: 10, name: "hello")
diff_author = AuthorWithCustomCacheKey.new(id: 11, name: "hello")

author_serializer = AuthorSerializer.new(author)
same_author_serializer = AuthorSerializer.new(same_author)
diff_author_serializer = AuthorSerializer.new(diff_author)
adapter = AuthorSerializer.serialization_adapter_instance

assert_equal(author_serializer.cache_key(adapter),
same_author_serializer.cache_key(adapter))
refute_equal(author_serializer.cache_key(adapter),
diff_author_serializer.cache_key(adapter))
end

def test_default_cache_key_fallback
render_object_with_cache(@comment)
key = "#{@comment.cache_key}/#{adapter.cache_key}"
Expand Down

0 comments on commit 2811e9e

Please sign in to comment.