Module: PgSearch::Multisearchable

Defined in:
lib/pg_search/multisearchable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/pg_search/multisearchable.rb', line 7

def self.included(mod)
  mod.class_eval do
    has_one :pg_search_document,
            as: :searchable,
            class_name: "PgSearch::Document",
            dependent: :delete

    after_save :update_pg_search_document,
               if: -> { PgSearch.multisearch_enabled? }
  end
end

Instance Method Details

#create_or_update_pg_search_documentObject



57
58
59
60
61
62
63
# File 'lib/pg_search/multisearchable.rb', line 57

def create_or_update_pg_search_document
  if !pg_search_document
    create_pg_search_document(pg_search_document_attrs)
  elsif should_update_pg_search_document?
    pg_search_document.update(pg_search_document_attrs)
  end
end

#pg_search_document_attrsObject



25
26
27
28
29
30
31
32
33
# File 'lib/pg_search/multisearchable.rb', line 25

def pg_search_document_attrs
  {
    content: searchable_text
  }.tap do |h|
    if (attrs = pg_search_multisearchable_options[:additional_attributes])
      h.merge! attrs.to_proc.call(self)
    end
  end
end

#searchable_textObject



19
20
21
22
23
# File 'lib/pg_search/multisearchable.rb', line 19

def searchable_text
  Array(pg_search_multisearchable_options[:against])
    .map { |symbol| send(symbol) }
    .join(" ")
end

#should_update_pg_search_document?Boolean



35
36
37
38
39
40
# File 'lib/pg_search/multisearchable.rb', line 35

def should_update_pg_search_document?
  return false if pg_search_document.destroyed?

  conditions = Array(pg_search_multisearchable_options[:update_if])
  conditions.all? { |condition| condition.to_proc.call(self) }
end

#update_pg_search_documentObject

rubocop:disable Metrics/AbcSize



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/pg_search/multisearchable.rb', line 42

def update_pg_search_document # rubocop:disable Metrics/AbcSize
  if_conditions = Array(pg_search_multisearchable_options[:if])
  unless_conditions = Array(pg_search_multisearchable_options[:unless])

  should_have_document =
    if_conditions.all? { |condition| condition.to_proc.call(self) } &&
    unless_conditions.all? { |condition| !condition.to_proc.call(self) }

  if should_have_document
    create_or_update_pg_search_document
  else
    pg_search_document&.destroy
  end
end