mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Adding cache support to version 0.10.0
It's a new implementation of cache based on ActiveSupport::Cache.
The implementation abstracts the cache in Adapter class on a
private method called cached_object, this method is intended
to be used on Adapters inside serializable_hash method in order
to cache each instance of the object that will be returned by
the serializer.
Some of its features are:
- A different syntax. (no longer need the cache_key method).
- An options argument that have the same arguments of ActiveSupport::Cache::Store, plus a key option that will be the prefix of the object cache on a pattern "#{key}-#{object.id}".
- It cache the objects individually and not the whole Serializer return, re-using it in different requests (as a show and a index method for example.)
This commit is contained in:
32
README.md
32
README.md
@@ -33,6 +33,7 @@ serializers:
|
||||
|
||||
```ruby
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
cache key: 'posts', expires_in: 3.hours
|
||||
attributes :title, :body
|
||||
|
||||
has_many :comments
|
||||
@@ -246,6 +247,37 @@ You may also use the `:serializer` option to specify a custom serializer class,
|
||||
The `url` declaration describes which named routes to use while generating URLs
|
||||
for your JSON. Not every adapter will require URLs.
|
||||
|
||||
## Caching
|
||||
|
||||
To cache a serializer, call ```cache``` and pass its options.
|
||||
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}"```.
|
||||
|
||||
**[NOTE] Every object is individually cached.**
|
||||
**[NOTE] The cache is automatically expired after update an object but it's not deleted.**
|
||||
|
||||
```ruby
|
||||
cache(options = nil) # options: ```{key, expires_in, compress, force, race_condition_ttl}```
|
||||
```
|
||||
|
||||
Take the example bellow:
|
||||
|
||||
```ruby
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
cache key: 'post', expires_in: 3.hours
|
||||
attributes :title, :body
|
||||
|
||||
has_many :comments
|
||||
|
||||
url :post
|
||||
end
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you find a bug, please report an [Issue](https://github.com/rails-api/active_model_serializers/issues/new).
|
||||
|
||||
Reference in New Issue
Block a user