Class: Warped::Queries::Search

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

Overview

Search for records in a scope

This class provides a way to search for records in a scope. It uses a scope in the model to perform the search.

By default, it uses the search scope in the model to perform the search. You can also specify a different scope to use for searching, like so:

Examples:

Warped::Queries::Search.call(User.all, search_term: "John")
# => #<ActiveRecord::Relation [...]>
Warped::Queries::Search.call(User.all, search_term: "John", model_search_scope: :search_by_name)
# => #<ActiveRecord::Relation [...]>

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, search_term:, model_search_scope: :search) ⇒ ActiveRecord::Relation

Returns the searched scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to search in

  • search_term (String)

    the term to search for

  • model_search_scope (String, Symbol) (defaults to: :search)

    the name of the scope to use for searching in the model



36
37
38
39
40
41
# File 'lib/warped/queries/search.rb', line 36

def initialize(scope, search_term:, model_search_scope: :search)
  super()
  @scope = scope
  @search_term = search_term
  @model_search_scope = model_search_scope
end

Class Method Details

.call(scope, search_term:, model_search_scope: :search) ⇒ ActiveRecord::Relation

Returns the searched scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to search in

  • search_term (String)

    the term to search for

  • model_search_scope (String, Symbol) (defaults to: :search)

    the name of the scope to use for searching in the model

Returns:

  • (ActiveRecord::Relation)

    the searched scope



28
29
30
# File 'lib/warped/queries/search.rb', line 28

def self.call(scope, search_term:, model_search_scope: :search)
  new(scope, search_term:, model_search_scope:).call
end

Instance Method Details

#callObject



43
44
45
46
47
48
49
# File 'lib/warped/queries/search.rb', line 43

def call
  return scope if search_term.blank?

  validate_model_search_scope!

  scope.public_send(model_search_scope, search_term)
end