Module: SearchAble

Extended by:
ActiveSupport::Concern
Included in:
AuditLog, Cron::Tab
Defined in:
lib/app/models/concerns/search_able.rb

Overview

Public: Add search and sort text to an object

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/app/models/concerns/search_able.rb', line 9

def self.included(base)
  base.class_eval do
    #
    # Fields
    #
    field :search_text, type: String
    field :sort_text, type: String
    #
    # Call backs
    #
    before_save :update_search_and_sort_text
  end
end

Instance Method Details

#after_search_textObject

Place holder to call to allow for work to be done after we gather up search text fields



50
# File 'lib/app/models/concerns/search_able.rb', line 50

def after_search_text; end

#before_search_textObject

Place holder to call to allow for work to be done before we gather up search text fields



45
# File 'lib/app/models/concerns/search_able.rb', line 45

def before_search_text; end

#search_fieldsObject

Internal: Which fields to add to search text

Examples

search_fields
# => ['name', 'email', 'code']

Return which fields should be added to search



103
104
105
# File 'lib/app/models/concerns/search_able.rb', line 103

def search_fields
  %w[name]
end

#sort_fieldsObject

Internal: Which fields to add to sort on

Examples

sort_fields
# => ['name', 'email']

Return which fields should be added to sort



117
118
119
# File 'lib/app/models/concerns/search_able.rb', line 117

def sort_fields
  search_fields
end

#update_search_and_sort_textObject

Internal: Update the search and sort text

Call before validation to update, changes are persisted with the object.



57
58
59
60
61
62
63
64
# File 'lib/app/models/concerns/search_able.rb', line 57

def update_search_and_sort_text
  return if destroyed?

  before_search_text
  update_text(search_fields, :search_text)
  update_text(sort_fields, :sort_text)
  after_search_text
end

#update_text(fields, field_to_update) ⇒ Object

Internal: Update the search text

Examples

update_search_text


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/app/models/concerns/search_able.rb', line 73

def update_text(fields, field_to_update)
  items = fields.reject { |field| send(field.to_sym).blank? }.collect do |field|
    value = send(field.to_sym)

    case value
    when String
      value.downcase
    when Integer, Float
      value.to_s.rjust(4, '0')
    when Array
      value.empty? ? nil : value.join(' ').downcase
    when Hash
      value.inspect
    else
      value.to_s
    end
  end
  send "#{field_to_update}=", items.compact.join(' ')
end