Module: Graphiform::ScopeComposer

Defined in:
lib/graphiform/scope_composer.rb

Overview

Builds an ActiveRecord relation by applying Graphiform/Scopiform-style customizations on top of a base relation.

Used by both PreloaderSource (to compose the ‘scope:` handed to ActiveRecord::Associations::Preloader) and Core#apply_built_ins (to apply the same chain to top-level resolver relations).

Class Method Summary collapse

Class Method Details

.compose(relation, scope: nil, where: nil, sort: nil, group: nil, includes: nil) ⇒ ActiveRecord::Relation

Parameters:

  • relation (ActiveRecord::Relation)

    starting relation (e.g. ‘Model.all`)

  • scope (Proc, nil) (defaults to: nil)

    optional scope block, ‘instance_exec`’d on the relation

  • where (Hash, nil) (defaults to: nil)

    Scopiform filter hash, applied via ‘apply_filters`

  • sort (Hash, nil) (defaults to: nil)

    Scopiform sort hash, applied via ‘apply_sorts`

  • includes (Symbol, Array, Hash, nil) (defaults to: nil)

    eager-load spec passed to ‘includes`

Returns:

  • (ActiveRecord::Relation)


19
20
21
22
23
24
25
26
# File 'lib/graphiform/scope_composer.rb', line 19

def compose(relation, scope: nil, where: nil, sort: nil, group: nil, includes: nil)
  relation = relation.merge(relation.instance_exec(&scope)) if scope.respond_to?(:call)
  relation = relation.includes(includes)                    if includes.present? && relation.respond_to?(:includes)
  relation = relation.apply_filters(where.to_h)             if where.present?    && relation.respond_to?(:apply_filters)
  relation = relation.apply_sorts(sort.to_h)                if sort.present?     && relation.respond_to?(:apply_sorts)
  relation = relation.apply_groupings(group.to_h)           if group.present?    && relation.respond_to?(:apply_groupings)
  relation
end

.customized?(scope: nil, where: nil, sort: nil, group: nil, includes: nil) ⇒ Boolean

True when any customization would actually modify the base relation. Used by PreloaderSource to decide whether to hand a scope to upstream (which disables result caching) or pass nil (which preserves it).

Returns:

  • (Boolean)


31
32
33
# File 'lib/graphiform/scope_composer.rb', line 31

def customized?(scope: nil, where: nil, sort: nil, group: nil, includes: nil)
  scope.respond_to?(:call) || where.present? || sort.present? || group.present? || includes.present?
end