Class: Warped::Queries::Filter

Inherits:
Object
  • Object
show all
Defined in:
lib/warped/queries/filter.rb

Overview

Filter a scope by a set of conditions

This class provides a simple interface for filtering a scope by a set of conditions. The conditions are passed as an array of hashes, where each hash contains the following keys:

  • relation: the relation to use for the filter (e.g. “eq”, “gt”, “in”, etc.)

  • field: the field to filter by

  • value: the value to filter by

To see the list of available relations, check the RELATIONS constant.

Examples:

Filter a scope by a set of conditions

Warped::Queries::Filter.call(User.all, filter_conditions: [
  { relation: "eq", field: :first_name, value: "John" },
  { relation: "gt", field: :age, value: 18 }
])
# => #<ActiveRecord::Relation [...]>

See Also:

Constant Summary collapse

RELATIONS =
::Warped::Filter::Base::RELATIONS.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, filter_conditions:) ⇒ ActiveRecord::Relation

Returns the filtered scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to filter

  • filter_conditions (Array<Hash>)

    the conditions to filter by



40
41
42
43
44
# File 'lib/warped/queries/filter.rb', line 40

def initialize(scope, filter_conditions:)
  super()
  @scope = scope
  @filter_conditions = filter_conditions
end

Class Method Details

.call(scope, filter_conditions:) ⇒ ActiveRecord::Relation

Returns the filtered scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to filter

  • filter_conditions (Array<Hash>)

    the conditions to filter by

Returns:

  • (ActiveRecord::Relation)

    the filtered scope



33
34
35
# File 'lib/warped/queries/filter.rb', line 33

def self.call(scope, filter_conditions:)
  new(scope, filter_conditions:).call
end

Instance Method Details

#callObject



46
47
48
49
50
51
52
53
54
55
# File 'lib/warped/queries/filter.rb', line 46

def call
  filter_conditions.reduce(scope) do |scope, filter_condition|
    relation = filter_condition[:relation].to_s
    field = filter_condition[:field]
    value = filter_condition[:value]

    validate_relation!(relation)
    filtered_scope(scope, relation, field, value)
  end
end