Module: PgSearchable::Model::Builder

Defined in:
lib/pg-searchable/model.rb

Constant Summary collapse

DISALLOWED_TSQUERY_CHARACTERS =
/['?\\:‘’]/.freeze

Class Method Summary collapse

Class Method Details

.dictionaryObject



55
56
57
# File 'lib/pg-searchable/model.rb', line 55

def self.dictionary
  Arel::Nodes.build_quoted(:simple)
end

.normalize(x) ⇒ Object



59
60
61
# File 'lib/pg-searchable/model.rb', line 59

def self.normalize(x)
  x # TODO
end

.tsquery(query, opts) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/pg-searchable/model.rb', line 63

def self.tsquery(query, opts)
  query_terms = query.split(" ").compact
  tsq =
    if query.blank?
      Arel::Nodes.build_quoted("")
    elsif opts[:raw] || opts[:websearch]
      Arel::Nodes.build_quoted(query)
    else
      tsquery_for_terms(query_terms, prefix: opts[:prefix])
    end
  
  fn_name = opts[:websearch] ? "websearch_to_tsquery" : "to_tsquery"
  Arel::Nodes::NamedFunction.new(fn_name, [dictionary, tsq])
end

.tsquery_expression(term, negated:, prefix:) ⇒ Object

After this, the SQL expression evaluates to a string containing the term surrounded by single-quotes. If :prefix is true, then the term will have :* appended to the end. If :negated is true, then the term will have ! prepended to the front.



101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/pg-searchable/model.rb', line 101

def self.tsquery_expression(term, negated:, prefix:)
  terms = [
    (Arel::Nodes.build_quoted('!') if negated),
    Arel::Nodes.build_quoted("' "),
    Arel::Nodes.build_quoted(term),
    Arel::Nodes.build_quoted(" '"),
    (Arel::Nodes.build_quoted(":*") if prefix)
  ].compact
  
  terms.inject do |memo, term|
    Arel::Nodes::InfixOperation.new("||", memo, Arel::Nodes.build_quoted(term))
  end
end

.tsquery_for_terms(terms, prefix:) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/pg-searchable/model.rb', line 78

def self.tsquery_for_terms(terms, prefix:)
  terms = terms.map { |term| tsquery_term(term, prefix: prefix) }
  terms.inject do |memo, term|
    term_anded = Arel::Nodes::InfixOperation.new("||", Arel::Nodes.build_quoted(" & "), term)
    Arel::Nodes::InfixOperation.new("||", memo, term_anded)
  end
end

.tsquery_term(unsanitized_term, prefix:) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/pg-searchable/model.rb', line 86

def self.tsquery_term(unsanitized_term, prefix:)
  negated = false
  
  if unsanitized_term.start_with?("!")
    unsanitized_term[0] = ''
    negated = true
  end
  
  sanitized_term = unsanitized_term.gsub(DISALLOWED_TSQUERY_CHARACTERS, " ")
  tsquery_expression(sanitized_term, negated: negated, prefix: prefix)
end