Module: Knuckles::Active::Hydrator

Extended by:
Hydrator
Included in:
Hydrator
Defined in:
lib/knuckles/active/hydrator.rb

Overview

The active hydrator converts minimal objects in a prepared collection into fully “hydrated” versions of the same record. For example, the initial ‘model` may only have the `id` and `updated_at` timestamp selected, which is ideal for fetching from the cache. If the object wasn’t in the cache then all of the fields are needed for a complete rendering, so the hydration call will use the passed relation to fetch the full model and any associations.

This ‘Hydrator` module is specifically designed to work with `ActiveRecord` relations. The initial objects can be anything that responds to `id`, but the relation should be an `ActiveRecord` relation.

Instance Method Summary collapse

Instance Method Details

#call(prepared, options) ⇒ Object

Convert all uncached objects into their full representation.

Examples:

Hydrating missing objects


relation = Post.all.preload(:author, :comments)
prepared = relation.select(:id, :updated_at)

Knuckles::Active::Hydrator.call(prepared, relation: relation) #=>
  # [{object: #Post<1>, cached?: false, ...

Parameters:

  • prepared (Enumerable)

    The prepared collection for processing

  • [#Relation] (Hash)

    a customizable set of options



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/knuckles/active/hydrator.rb', line 33

def call(prepared, options)
  mapping = id_object_mapping(prepared)

  if mapping.any?
    relation = relation_without_pagination(options)

    relation.where(id: mapping.keys).each do |hydrated|
      mapping[hydrated.id][:object] = hydrated
    end
  end

  prepared
end