Class: AutoPreload::Adapters::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/auto_preload/adapters/serializer.rb

Overview

This class takes a model and finds all the preloadable associations.

Instance Method Summary collapse

Constructor Details

#initializeSerializer

Returns a new instance of Serializer.



9
10
11
# File 'lib/auto_preload/adapters/serializer.rb', line 9

def initialize
  @fallback = ActiveRecord.new
end

Instance Method Details

#resolve_preloadables(model, options = {}) ⇒ Array<ActiveRecord::Reflection>

Returns The preloadable associations.

Parameters:

  • model (ActiveRecord::Base)

    The model to find preloadable associations for.

Returns:

  • (Array<ActiveRecord::Reflection>)

    The preloadable associations.



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/auto_preload/adapters/serializer.rb', line 15

def resolve_preloadables(model, options = {})
  serializer = resolve_serializer(model, options)
  preloadables = @fallback.resolve_preloadables(model)
  return preloadables unless serializer

  preloadables_map = preloadables.index_by(&:name)

  serializer._reflections.map do |key, _|
    preloadables_map[key]
  end.compact
end

#resolve_serializer(model, options = {}) ⇒ ActiveModel::Serializer

Parameters:

  • model (ActiveRecord::Base)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :root (Boolean)
  • :serializer (ActiveModel::Serializer)

Returns:

  • (ActiveModel::Serializer)


32
33
34
35
36
37
38
# File 'lib/auto_preload/adapters/serializer.rb', line 32

def resolve_serializer(model, options = {})
  if options[:root]
    options[:serializer] || ActiveModel::Serializer.serializer_for(model)
  else
    ActiveModel::Serializer.serializer_for(model)
  end
end