Module: BlueprinterActiveRecord::QueryMethods

Defined in:
lib/blueprinter-activerecord/query_methods.rb

Defined Under Namespace

Modules: Delegates

Constant Summary collapse

ACTIONS =
%i(preload eager_load includes).freeze

Instance Method Summary collapse

Instance Method Details

#before_preload_blueprintObject

Get the preloads present before the Preloader extension ran (internal, for PreloadLogger)



60
61
62
# File 'lib/blueprinter-activerecord/query_methods.rb', line 60

def before_preload_blueprint
  @values[:before_preload_blueprint]
end

#before_preload_blueprint=(val) ⇒ Object

Set the preloads present before the Preloader extension ran (internal, for PreloadLogger)



65
66
67
# File 'lib/blueprinter-activerecord/query_methods.rb', line 65

def before_preload_blueprint=(val)
  @values[:before_preload_blueprint] = val
end

#preload_blueprint(blueprint = nil, view = :default, use: :preload) ⇒ ActiveRecord::Relation

Automatically preload (or ‘eager_load` or `includes`) the associations in the given blueprint and view (recursively).

You can have the Blueprint and view autodetected on render:

q = Widget.where(...).preload_blueprint
WidgetBlueprint.render(q, view: :extended)

Or you can pass them up front:

widgets = Widget.where(...).preload_blueprint(WidgetBlueprint, :extended).to_a
# do something with widgets, then render
WidgetBlueprint.render(widgets, view: :extended)

Parameters:

  • blueprint (Class) (defaults to: nil)

    The Blueprinter class to use (ignore to autodetect on render)

  • view (Symbol) (defaults to: :default)

    The Blueprinter view name to use (ignore to autodetect on render)

  • use (Symbol) (defaults to: :preload)

    The eager loading strategy to use (:preload, :includes, :eager_load)

Returns:

  • (ActiveRecord::Relation)


33
34
35
# File 'lib/blueprinter-activerecord/query_methods.rb', line 33

def preload_blueprint(blueprint = nil, view = :default, use: :preload)
  spawn.preload_blueprint!(blueprint, view, use: use)
end

#preload_blueprint!(blueprint = nil, view = :default, use: :preload) ⇒ Object

See preload_blueprint



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/blueprinter-activerecord/query_methods.rb', line 38

def preload_blueprint!(blueprint = nil, view = :default, use: :preload)
  unless ACTIONS.include? use
    valid = ACTIONS.map(&:inspect).join(", ")
    raise BlueprinterError, "Unknown `preload_blueprint` method :#{use}. Valid methods are #{valid}."
  end

  if blueprint and view
    # preload right now
    preloads = Preloader.preloads(blueprint, view, model: model)
    public_send(use, preloads)
  else
    # preload during render
    @values[:preload_blueprint_method] = use
    self
  end
end

#preload_blueprint_methodObject



55
56
57
# File 'lib/blueprinter-activerecord/query_methods.rb', line 55

def preload_blueprint_method
  @values[:preload_blueprint_method]
end