Class: ActiveElement::Components::TextSearch::Sql

Inherits:
Object
  • Object
show all
Defined in:
lib/active_element/components/text_search/sql.rb

Overview

Encapsulates generation of database adapter-specific sanitized SQL queries for performing full text searches. Identifies columns and adapters where ‘LIKE` or `ILIKE` can be applied and generates a whereclause according to the provided parameters.

Receives an ActiveRecord model class, a query (a string used to match results), attribute columns to match against, and a value column to return in the results.

Inspects ActiveRecord metadata to match field names to column objects.

Instance Method Summary collapse

Constructor Details

#initialize(model:, query:, value:, attributes:) ⇒ Sql

Returns a new instance of Sql.



15
16
17
18
19
20
# File 'lib/active_element/components/text_search/sql.rb', line 15

def initialize(model:, query:, value:, attributes:)
  @model = model
  @query = query
  @value = value
  @attributes = attributes
end

Instance Method Details

#search_columnsObject



28
29
30
31
32
# File 'lib/active_element/components/text_search/sql.rb', line 28

def search_columns
  return [] if attributes.blank?

  @search_columns ||= attributes.map { |attribute| column_for(attribute) }.compact
end

#value_columnObject



22
23
24
25
26
# File 'lib/active_element/components/text_search/sql.rb', line 22

def value_column
  return nil if value.blank?

  @value_column ||= model&.columns&.find { |column| column.name == value }
end

#whereclauseObject



34
35
36
37
# File 'lib/active_element/components/text_search/sql.rb', line 34

def whereclause
  clauses = search_columns.map { |column| "#{column.name} #{operator(column)} ?" }
  [clauses.join(' OR '), search_columns.map { |column| search_param(column) }].flatten
end