Class: ActiveElement::DefaultController::Search

Inherits:
Object
  • Object
show all
Defined in:
lib/active_element/default_controller/search.rb

Overview

Full text search and datetime querying for DefaultController, provides full text search filters for all controllers with configured searchable fields. Includes support for querying across relations.

Instance Method Summary collapse

Constructor Details

#initialize(controller:, model:) ⇒ Search

Returns a new instance of Search.



9
10
11
12
# File 'lib/active_element/default_controller/search.rb', line 9

def initialize(controller:, model:)
  @controller = controller
  @model = model
end

Instance Method Details

#search_filtersObject



14
15
16
17
18
# File 'lib/active_element/default_controller/search.rb', line 14

def search_filters
  @search_filters ||= controller.params.permit(*searchable_fields).transform_values do |value|
    value.try(:compact_blank) || value
  end.compact_blank
end

#search_relationsObject



39
40
41
42
# File 'lib/active_element/default_controller/search.rb', line 39

def search_relations
  relation_joins = search_filters.to_h.keys.map { |key| relation?(key) ? key.to_sym : nil }.compact
  (relation_joins + shorthand_joins).uniq
end

#shorthand_joinsObject



44
45
46
47
48
49
# File 'lib/active_element/default_controller/search.rb', line 44

def shorthand_joins
  search_filters.to_h
                .keys
                .select { |key| key.to_s.include?('.') }
                .map { |key| key.partition('.').first.to_sym }
end

#text_searchObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_element/default_controller/search.rb', line 24

def text_search
  conditions = search_filters.to_h.map do |key, value|
    next relation_matches(key, value) if relation?(key)
    next datetime_between(key, value) if datetime?(key)
    next join(key, value) if key.to_s.include?('.')
    next model.arel_table[key].matches("#{value}%") if string_like_column?(key)

    model.arel_table[key].eq(value)
  end

  conditions[1..].reduce(conditions.first) do |accumulated, condition|
    accumulated.and(condition)
  end
end

#text_search?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/active_element/default_controller/search.rb', line 20

def text_search?
  search_filters.present?
end