项目作者: foca

项目描述 :
Cache the output of your Granola serializers.
高级语言: Ruby
项目地址: git://github.com/foca/granola-cache.git
创建时间: 2016-11-21T03:44:11Z
项目社区:https://github.com/foca/granola-cache

开源协议:MIT License

下载


Granola::Cache Build Status RubyGem

Provide caching options for the result of your Granola serializers.

Example

  1. class PersonSerializer < Granola::Serializer
  2. cache key: "person", expire_in: 3600
  3. def data
  4. {
  5. id: object.id,
  6. name: object.name,
  7. }
  8. end
  9. def cache_key
  10. "%s:%s" % [object.id, object.updated_at.to_i]
  11. end
  12. end
  13. serializer = PersonSerializer.new(person)
  14. serializer.to_json # Generates JSON and stores it in the cache.
  15. serializer.to_json # Retreives from cache without rendering.
  16. person.update(...) # Do something that would change the `cache_key` (e.g. update
  17. # the object's `updated_at`.)
  18. serializer.to_json # Generates JSON again, storing the new version in the cache.

NOTE: Changing the cache key will invalidate previous versions of the cached
object, but will not delete them from the cache store.

Install

  1. gem install granola-cache

Cache Stores

By default, Granola::Cache stores cached output from serializers in an in-memory
Hash. This is not meant for production use. You should provide an alternative
store for your application.

Alternative stores should implement a single method:

  1. fetch(key, options = {}, &block)

Where:

  • key: The cache key to fetch from cache.
  • options: Any options the cache store can take (for example, :expire_in
    if your store supports Time-based expiration.)

If the key isn’t found in the store, the block is invoked, and the result from
this block is both returned and stored in the cache for further use.

There’s an example Redis Store included in this
repository, should you wish to inspect it.

Rails

This is compatible with ActiveSupport::Cache::Store, so if you’re in a Rails
application, you can just do this in config/initializers/granola.rb:

  1. Granola::Cache.store = Rails.cache

Cache Options

Pass caching options to a serializer by calling the cache singleton method.

Granola::Cache only recognizes these options: :key and :store. Any other
option passed will be ignored by Granola, but forwarded to the cache
store
.

:key

This is meant to be a prefix applied to cache keys. In the example above, any
particular serializer will be stored in the cache with the following key:

  1. "#{key}/#{object.id}:#{object.updated_at.to_i}"

:store

This allows overriding the caching store for a specific serializer.

  1. class WeeklyReportSerializer < Granola::Serializer
  2. cache store: DifferentStore.new
  3. end

See Cache Stores for more on configuring the global store.

License

This project is shared under the MIT license. See the attached LICENSE file
for details.