Skip to content

Commit

Permalink
Adding Fragment Cache to AMS
Browse files Browse the repository at this point in the history
It's an upgrade based on the new Cache implementation rails-api#693.
It allows to use the Rails conventions to cache
specific attributes or associations.
It's based on the Cache Composition implementation.
  • Loading branch information
joaomdmoura committed Mar 23, 2015
1 parent b68d7f4 commit 4ea1b98
Show file tree
Hide file tree
Showing 18 changed files with 451 additions and 71 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,10 @@ The options are the same options of ```ActiveSupport::Cache::Store```, plus
a ```key``` option that will be the prefix of the object cache
on a pattern ```"#{key}/#{object.id}-#{object.updated_at}"```.

The cache support is optimized to use the cached object in multiple request. An object cached on an ```show``` request will be reused at the ```index```. If there is a relationship with another cached serializer it will also be created and reused automatically.

**[NOTE] Every object is individually cached.**

**[NOTE] The cache is automatically expired after update an object but it's not deleted.**

```ruby
Expand All @@ -295,6 +298,27 @@ On this example every ```Post``` object will be cached with
the key ```"post/#{post.id}-#{post.updated_at}"```. You can use this key to expire it as you want,
but in this case it will be automatically expired after 3 hours.

### Fragmenting Caching

If there is some API endpoint that shouldn't be fully cached, you can still optmise it, using Fragment Cache on the attributes and relationships that you want to cache.

You can define the attribute by using ```only``` or ```except``` option on cache method.

**[NOTE] Cache serializers will be used at their relationships**

Example:

```ruby
class PostSerializer < ActiveModel::Serializer
cache key: 'post', expires_in: 3.hours, only: [:title]
attributes :title, :body

has_many :comments

url :post
end
```

## Getting Help

If you find a bug, please report an [Issue](https://github.com/rails-api/active_model_serializers/issues/new).
Expand Down
12 changes: 10 additions & 2 deletions lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,25 @@ class Serializer

class << self
attr_accessor :_attributes
attr_accessor :_attributes_keys
attr_accessor :_associations
attr_accessor :_urls
attr_accessor :_cache
attr_accessor :_cache_key
attr_accessor :_cache_only
attr_accessor :_cache_except
attr_accessor :_cache_options
end

def self.inherited(base)
base._attributes = []
base._attributes_keys = {}
base._associations = {}
base._urls = []
end

def self.attributes(*attrs)
attrs = attrs.first if attrs.first.class == Array
@_attributes.concat attrs

attrs.each do |attr|
Expand All @@ -35,6 +40,7 @@ def self.attributes(*attrs)

def self.attribute(attr, options = {})
key = options.fetch(:key, attr)
@_attributes_keys[attr] = {key: key} if key != attr
@_attributes.concat [key]
define_method key do
object.read_attribute_for_serialization(attr)
Expand All @@ -43,8 +49,10 @@ def self.attribute(attr, options = {})

# Enables a serializer to be automatically cached
def self.cache(options = {})
@_cache = ActionController::Base.cache_store if Rails.configuration.action_controller.perform_caching
@_cache_key = options.delete(:key)
@_cache = ActionController::Base.cache_store if Rails.configuration.action_controller.perform_caching
@_cache_key = options.delete(:key)
@_cache_only = options.delete(:only)
@_cache_except = options.delete(:except)
@_cache_options = (options.empty?) ? nil : options
end

Expand Down
46 changes: 32 additions & 14 deletions lib/active_model/serializer/adapter.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'active_model/serializer/adapter/fragment_cache'

module ActiveModel
class Serializer
class Adapter
Expand Down Expand Up @@ -32,8 +34,38 @@ def self.adapter_class(adapter)
"ActiveModel::Serializer::Adapter::#{adapter.to_s.classify}".safe_constantize
end

def fragment_cache(*args)
raise NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.'
end

private

def cache_check(serializer)
@serializer = serializer
@klass = serializer.class
if is_cached?
@klass._cache.fetch(cache_key, @klass._cache_options) do
yield
end
elsif is_fragment_cached?
FragmentCache.new(self, @serializer, @options, @root).fetch
else
yield
end
end

def is_cached?
@klass._cache && !@klass._cache_only && !@klass._cache_except
end

def is_fragment_cached?
@klass._cache_only && !@klass._cache_except || !@klass._cache_only && @klass._cache_except
end

def cache_key
(@klass._cache_key) ? "#{@klass._cache_key}/#{@serializer.object.id}-#{@serializer.object.updated_at}" : @serializer.object.cache_key
end

def meta
serializer.meta if serializer.respond_to?(:meta)
end
Expand All @@ -50,20 +82,6 @@ def include_meta(json)
json[meta_key] = meta if meta && root
json
end

private

def cached_object
klass = serializer.class
if klass._cache
_cache_key = (klass._cache_key) ? "#{klass._cache_key}/#{serializer.object.id}-#{serializer.object.updated_at}" : serializer.object.cache_key
klass._cache.fetch(_cache_key, klass._cache_options) do
yield
end
else
yield
end
end
end
end
end
74 changes: 74 additions & 0 deletions lib/active_model/serializer/adapter/fragment_cache.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
module ActiveModel
class Serializer
class Adapter
class FragmentCache

attr_reader :serializer

def initialize(adapter, serializer, options, root)
@root = root
@options = options
@adapter = adapter
@serializer = serializer
end

def fetch
klass = serializer.class
# It will split the serializer into two, one that will be cached and other wont
serializers = fragment_serializer(@serializer.object.class.name, klass)

# Instanciate both serializers
cached_serializer = serializers[:cached].constantize.new(@serializer.object)
non_cached_serializer = serializers[:non_cached].constantize.new(@serializer.object)

cached_adapter = @adapter.class.new(cached_serializer, @options)
non_cached_adapter = @adapter.class.new(non_cached_serializer, @options)

# Get serializable hash from both
cached_hash = cached_adapter.serializable_hash
non_cached_hash = non_cached_adapter.serializable_hash

# Merge both results
@adapter.fragment_cache(cached_hash, non_cached_hash)
end

private

def cached_attributes_and_association(klass, serializers)
cached_attributes = (klass._cache_only) ? klass._cache_only : @serializer.attributes.keys.delete_if {|attr| klass._cache_except.include?(attr) }
non_cached_attributes = @serializer.attributes.keys.delete_if {|attr| cached_attributes.include?(attr) }

cached_attributes.each do |attribute|
options = @serializer.class._attributes_keys[attribute]
options ||= {}
# Add cached attributes to cached Serializer
serializers[:cached].constantize.attribute(attribute, options)
end

non_cached_attributes.each do |attribute|
options = @serializer.class._attributes_keys[attribute]
options ||= {}
# Add non-cached attributes to non-cached Serializer
serializers[:non_cached].constantize.attribute(attribute, options)
end
end

def fragment_serializer(name, klass)
cached = "#{name.capitalize}CachedSerializer"
non_cached = "#{name.capitalize}NonCachedSerializer"

Object.const_set cached, Class.new(ActiveModel::Serializer) unless Object.const_defined?(cached)
Object.const_set non_cached, Class.new(ActiveModel::Serializer) unless Object.const_defined?(non_cached)

klass._cache_options ||= {}
klass._cache_options[:key] = klass._cache_key if klass._cache_key
cached.constantize.cache(klass._cache_options)

serializers = {cached: cached, non_cached: non_cached}
cached_attributes_and_association(klass, serializers)
serializers
end
end
end
end
end
42 changes: 28 additions & 14 deletions lib/active_model/serializer/adapter/json.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'active_model/serializer/adapter/json/fragment_cache'

module ActiveModel
class Serializer
class Adapter
Expand All @@ -6,31 +8,43 @@ def serializable_hash(options = {})
if serializer.respond_to?(:each)
@result = serializer.map{|s| self.class.new(s).serializable_hash }
else
@result = cached_object do
@hash = serializer.attributes(options)
serializer.each_association do |name, association, opts|
if association.respond_to?(:each)
array_serializer = association
@hash[name] = array_serializer.map { |item| item.attributes(opts) }
else
if association
@hash[name] = association.attributes(options)
else
@hash[name] = nil
@hash = {}

@core = cache_check(serializer) do
serializer.attributes(options)
end

serializer.each_association do |name, association, opts|
if association.respond_to?(:each)
array_serializer = association
@hash[name] = array_serializer.map do |item|
cache_check(item) do
item.attributes(opts)
end
end
else
if association
@hash[name] = cache_check(association) do
association.attributes(options)
end
else
@hash[name] = nil
end
end
@hash
end
@result = @core.merge @hash
end

if root = options.fetch(:root, serializer.json_key)
@result = { root => @result }
end

@result
end
end

def fragment_cache(cached_hash, non_cached_hash)
Json::FragmentCache.new().fragment_cache(cached_hash, non_cached_hash)
end
end
end
end
end
15 changes: 15 additions & 0 deletions lib/active_model/serializer/adapter/json/fragment_cache.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module ActiveModel
class Serializer
class Adapter
class Json < Adapter
class FragmentCache

def fragment_cache(cached_hash, non_cached_hash)
non_cached_hash.merge cached_hash
end

end
end
end
end
end
31 changes: 19 additions & 12 deletions lib/active_model/serializer/adapter/json_api.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'active_model/serializer/adapter/json_api/fragment_cache'

module ActiveModel
class Serializer
class Adapter
Expand All @@ -23,15 +25,17 @@ def serializable_hash(options = {})
self.class.new(s, @options.merge(top: @top, fieldset: @fieldset)).serializable_hash[@root]
end
else
@hash = cached_object do
@hash[@root] = attributes_for_serializer(serializer, @options)
add_resource_links(@hash[@root], serializer)
@hash
end
@hash[@root] = attributes_for_serializer(serializer, @options)
add_resource_links(@hash[@root], serializer)
end
@hash
end

def fragment_cache(cached_hash, non_cached_hash)
root = false if @options.include?(:include)
JsonApi::FragmentCache.new().fragment_cache(root, cached_hash, non_cached_hash)
end

private

def add_links(resource, name, serializers)
Expand Down Expand Up @@ -91,22 +95,25 @@ def add_linked(resource_name, serializers, parent = nil)
end
end


def attributes_for_serializer(serializer, options)
if serializer.respond_to?(:each)
result = []
serializer.each do |object|
options[:fields] = @fieldset && @fieldset.fields_for(serializer)
attributes = object.attributes(options)
attributes[:id] = attributes[:id].to_s if attributes[:id]
result << attributes
result << cache_check(object) do
attributes = object.attributes(options)
attributes[:id] = attributes[:id].to_s if attributes[:id]
result << attributes
end
end
else
options[:fields] = @fieldset && @fieldset.fields_for(serializer)
result = serializer.attributes(options)
result[:id] = result[:id].to_s if result[:id]
result = cache_check(serializer) do
result = serializer.attributes(options)
result[:id] = result[:id].to_s if result[:id]
result
end
end

result
end

Expand Down
22 changes: 22 additions & 0 deletions lib/active_model/serializer/adapter/json_api/fragment_cache.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module ActiveModel
class Serializer
class Adapter
class JsonApi < Adapter
class FragmentCache

def fragment_cache(root, cached_hash, non_cached_hash)
hash = {}
core_cached = cached_hash.first
core_non_cached = non_cached_hash.first
no_root_cache = cached_hash.delete_if {|key, value| key == core_cached[0] }
no_root_non_cache = non_cached_hash.delete_if {|key, value| key == core_non_cached[0] }
cached_resource = (core_cached[1]) ? core_cached[1].merge(core_non_cached[1]) : core_non_cached[1]
hash = (root) ? { root => cached_resource } : cached_resource
hash.merge no_root_non_cache.merge no_root_cache
end

end
end
end
end
end
Loading

0 comments on commit 4ea1b98

Please sign in to comment.