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, key: UNDEFINED, collection: nil, status: nil, meta: {}, meta_key: :meta, **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

  • key (Symbol) (defaults to: UNDEFINED)

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

  • collection (Boolean) (defaults to: nil)

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

  • status (Integer, Symbol) (defaults to: nil)

    the HTTP response status code or Rails-supported symbol. See guides.rubyonrails.org/layouts_and_rendering.html#the-status-option

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

    data to include as metadata under a root key

  • meta_key (Symbol) (defaults to: :meta)

    they key to store the metadata under

  • options (Hash)

    any optional values from the serializer instance



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cache_crispies/controller.rb', line 30

def cache_render(
  serializer,
  cacheable,
  key: UNDEFINED, collection: nil, status: nil,
  meta: {}, meta_key: :meta,
  **options
)
  plan = CacheCrispies::Plan.new(
    serializer,
    cacheable,
    key: key, collection: collection,
    **options
  )

  if CacheCrispies.config.etags?
    response.weak_etag = plan.etag
  end

  serializer_json =
    if plan.collection?
      plan.cache do
        CacheCrispies::Collection.new(
          cacheable, serializer, options
        ).as_json
      end
    else
      plan.cache { serializer.new(cacheable, options).as_json }
    end

  json_hash = plan.wrap(serializer_json)
  json_hash[meta_key] = meta if meta.present?

  render_hash = { json: Oj.dump(json_hash, mode: OJ_MODE) }
  render_hash[:status] = status if status

  render render_hash
end