Module: SaDetector::ActiveRecord::ClassMethods
- Defined in:
- lib/sa_detector/active_record.rb
Instance Method Summary collapse
Instance Method Details
#searchable_and_sortable_by(attribute) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/sa_detector/active_record.rb', line 22 def searchable_and_sortable_by attribute @@attribute = attribute class << self define_method "search_and_sort_with" do |query| query = query.to_s.downcase result = self.where("LOWER(#{self.table_name}.#{@@attribute}) LIKE ?", "%#{query}%") result.size > 0 ? self.sort_for_search_results(result, query) : [] end define_method "sort_for_search_results" do |result, query| result.sort{ |a,b| a[@@attribute].downcase.index(query) <=> b[@@attribute].downcase.index(query) } end end end |
#searchable_by(*attributes) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/sa_detector/active_record.rb', line 8 def searchable_by *attributes @@attributes = attributes class << self define_method "search_with" do |query| query = query.to_s.downcase sql = [@@attributes.map{ |attribute| "LOWER(#{self.table_name}.#{attribute}) LIKE ?" }.join(" OR ")] sql += Array.new(@@attributes.count, "%#{query}%") self.where(sql) end end end |