Class: Plutonium::Query::Filters::Text

Inherits:
Plutonium::Query::Filter show all
Defined in:
lib/plutonium/query/filters/text.rb

Direct Known Subclasses

Definition::Base::TextFilter

Constant Summary collapse

VALID_PREDICATES =
[
  :eq,           # Equal
  :not_eq,       # Not equal
  :matches,      # LIKE with wildcards
  :not_matches,  # NOT LIKE with wildcards
  :starts_with,  # LIKE with suffix wildcard
  :ends_with,    # LIKE with prefix wildcard
  :contains,     # LIKE with wildcards on both sides
  :not_contains # NOT LIKE with wildcards on both sides
].freeze

Instance Attribute Summary

Attributes inherited from Plutonium::Query::Filter

#key

Instance Method Summary collapse

Methods included from Definition::Presentable

#description, #icon, #label

Constructor Details

#initialize(predicate: :eq) ⇒ Text

Returns a new instance of Text.



16
17
18
19
20
21
22
# File 'lib/plutonium/query/filters/text.rb', line 16

def initialize(predicate: :eq, **)
  super(**)
  unless VALID_PREDICATES.include?(predicate)
    raise ArgumentError, "unsupported predicate #{predicate}. Valid predicates are: #{VALID_PREDICATES.join(", ")}"
  end
  @predicate = predicate
end

Instance Method Details

#apply(scope, query:) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/plutonium/query/filters/text.rb', line 24

def apply(scope, query:)
  case @predicate
  when :eq
    scope.where(key => query)
  when :not_eq
    scope.where.not(key => query)
  when :matches
    scope.where("#{key} LIKE ?", query.tr("*", "%"))
  when :not_matches
    scope.where.not("#{key} LIKE ?", query.tr("*", "%"))
  when :starts_with
    scope.where("#{key} LIKE ?", "#{sanitize_like(query)}%")
  when :ends_with
    scope.where("#{key} LIKE ?", "%#{sanitize_like(query)}")
  when :contains
    scope.where("#{key} LIKE ?", "%#{sanitize_like(query)}%")
  when :not_contains
    scope.where.not("#{key} LIKE ?", "%#{sanitize_like(query)}%")
  else
    raise NotImplementedError, "text filter predicate #{@predicate}"
  end
end

#customize_inputsObject



47
48
49
50
# File 'lib/plutonium/query/filters/text.rb', line 47

def customize_inputs
  input :query
  field :query, placeholder: generate_placeholder
end