Module: SearchAble
- Extended by:
- ActiveSupport::Concern
- 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
-
#search_fields ⇒ Object
Internal: Which fields to add to search text.
-
#sort_fields ⇒ Object
Internal: Which fields to add to sort on.
-
#update_search_and_sort_text ⇒ Object
Internal: Update the search and sort text.
-
#update_text(fields, field_to_update) ⇒ Object
Internal: Update the search text.
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_validation :update_search_and_sort_text end end |
Instance Method Details
#search_fields ⇒ Object
Internal: Which fields to add to search text
Examples
search_fields
# => ['name', 'email', 'code']
Return which fields should be added to search
89 90 91 |
# File 'lib/app/models/concerns/search_able.rb', line 89 def search_fields %w[name] end |
#sort_fields ⇒ Object
Internal: Which fields to add to sort on
Examples
sort_fields
# => ['name', 'email']
Return which fields should be added to sort
103 104 105 |
# File 'lib/app/models/concerns/search_able.rb', line 103 def sort_fields search_fields end |
#update_search_and_sort_text ⇒ Object
Internal: Update the search and sort text
Call before validation to update, changes are persisted with the object.
47 48 49 50 51 52 |
# File 'lib/app/models/concerns/search_able.rb', line 47 def update_search_and_sort_text return if destroyed? update_text(search_fields, :search_text) update_text(sort_fields, :sort_text) end |
#update_text(fields, field_to_update) ⇒ Object
Internal: Update the search text
Examples
update_search_text
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/app/models/concerns/search_able.rb', line 61 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 else value.to_s end end send "#{field_to_update}=", items.compact.join(' ') end |