Module: CacheCrispies::Controller

Extended by:
ActiveSupport::Concern
Defined in:
lib/cache_crispies/controller.rb

Overview

A Rails concern designed to be used in Rails controllers to provide access to the #cache_render method

Constant Summary collapse

OJ_MODE =

The serialization mode that should be used with the oj gem

:rails

Instance Method Summary collapse

Instance Method Details

#cache_render(serializer, cacheable, options = {}) ⇒ void

This method returns an undefined value.

Renders the provided cacheable object to JSON using the provided serializer

Parameters:

  • serializer (CacheCrispies::Base)

    a class inheriting from CacheCrispies::Base

  • cacheable (Object)

    can be any object. But is typically a Rails model inheriting from ActiveRecord::Base

  • options (Hash) (defaults to: {})

    any optional values from the serializer instance

Options Hash (options):

  • :key (Symbol)

    the name of the root key to nest the JSON data under

  • :collection (Boolean)

    whether to render the data as a collection/array or a single object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cache_crispies/controller.rb', line 25

def cache_render(serializer, cacheable, options = {})
  plan = CacheCrispies::Plan.new(serializer, cacheable, options)

  # TODO: It would probably be good to add configuration to etiher
  # enable or disable this
  response.weak_etag = plan.etag

  serializer_json =
    if plan.collection?
      cacheable.map do |one_cacheable|
        plan.cache { serializer.new(one_cacheable, options).as_json }
      end
    else
      plan.cache { serializer.new(cacheable, options).as_json }
    end

  render json: Oj.dump(plan.wrap(serializer_json), mode: OJ_MODE)
end