Module: SearchableBy::Concern

Defined in:
lib/searchable_by/concern.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

:nodoc:



3
4
5
6
7
# File 'lib/searchable_by/concern.rb', line 3

def self.extended(base) # :nodoc:
  base.class_attribute :_searchable_by_profiles, instance_accessor: false, instance_predicate: false
  base._searchable_by_profiles = Profiles.new
  super
end

Instance Method Details

#inherited(base) ⇒ Object

:nodoc:



9
10
11
12
# File 'lib/searchable_by/concern.rb', line 9

def inherited(base) # :nodoc:
  base._searchable_by_profiles = _searchable_by_profiles.dup
  super
end

#search_by(query, profile: :default) ⇒ ActiveRecord::Relation

Returns the scoped relation.

Parameters:

  • query (String)

    the search query

Returns:

  • (ActiveRecord::Relation)

    the scoped relation



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/searchable_by/concern.rb', line 21

def search_by(query, profile: :default)
  config  = _searchable_by_profiles[profile]
  columns = config.columns
  return all if columns.empty?

  values = Util.norm_values(query, min_length: config.min_length).first(config.max_terms)
  return all if values.empty?

  columns.each do |col|
    col.node ||= col.attr.is_a?(Proc) ? col.attr.call : arel_table[col.attr]
  end
  clauses = Util.build_clauses(columns, values)
  return all if clauses.empty?

  scope = instance_exec(&config.scoping)
  clauses.each do |clause|
    scope = scope.where(clause)
  end
  scope
end

#searchable_by(profile = :default, max_terms: nil, min_length: 0, **options, &block) ⇒ Object



14
15
16
17
# File 'lib/searchable_by/concern.rb', line 14

def searchable_by(profile = :default, max_terms: nil, min_length: 0, **options, &block)
  _searchable_by_profiles[profile].configure(max_terms, min_length, **options, &block)
  _searchable_by_profiles
end