Class: LcpRuby::Search::ParameterizedScopeApplicator

Inherits:
Object
  • Object
show all
Defined in:
lib/lcp_ruby/search/parameterized_scope_applicator.rb

Class Method Summary collapse

Class Method Details

.apply(scope, scope_params, model_class, model_definition, evaluator:) ⇒ ActiveRecord::Relation

Applies parameterized scopes from request params to a query scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the current query scope

  • scope_params (Hash)

    raw params hash, e.g. { “created_recently” => { “days” => “30” } }

  • model_class (Class)

    the AR model class

  • model_definition (Metadata::ModelDefinition)
  • evaluator (Authorization::PermissionEvaluator)

Returns:

  • (ActiveRecord::Relation)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/lcp_ruby/search/parameterized_scope_applicator.rb', line 12

def self.apply(scope, scope_params, model_class, model_definition, evaluator:)
  return scope if scope_params.blank?

  scope_params.each do |scope_name, raw_params|
    scope_config = model_definition.parameterized_scope(scope_name)
    next unless scope_config

    raw_params = raw_params.to_unsafe_h if raw_params.respond_to?(:to_unsafe_h)
    raw_params = {} unless raw_params.is_a?(Hash)

    parameters = scope_config["parameters"] || []
    cast_params = cast_parameters(parameters, raw_params)

    # Skip if required params are missing
    next if missing_required?(parameters, cast_params)

    # Try filter_* interceptor first, then direct scope
    interceptor = "filter_#{scope_name}"
    if model_class.respond_to?(interceptor)
      scope = model_class.send(interceptor, scope, cast_params, evaluator)
    elsif model_class.respond_to?(scope_name)
      scope = invoke_scope(scope, scope_name, cast_params)
    else
      Rails.logger.warn(
        "[LcpRuby::ParameterizedScopeApplicator] Scope '#{scope_name}' " \
        "not found on model #{model_class.name}"
      )
    end
  end

  scope
end