Module: Toolbox::Searching

Defined in:
lib/toolbox/searching.rb

Defined Under Namespace

Modules: ControllerClassMethods, ControllerInstanceMethods, HelperMethods

Class Method Summary collapse

Class Method Details

.create_search_condition(filter, widgets_list) ⇒ Object

Creates a SQL where condition with the given filter and a list of fields filter: the text to search for. Separated multiple value by space widgets_list: an instance of Toolbox::WidgetList. See ControllerClassMethods::search_fields for more information about the syntax. Example:

search_field :firstname, :lastname, :address
create_search_condition('dav ny')

-> (firstname like ‘dav’ or lastname like ‘dav’ or address like ‘dav’) and (firstname like ‘ny’ or lastname like ‘ny’ or address like ‘ny’)



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/toolbox/searching.rb', line 23

def self.create_search_condition(filter, widgets_list)
  raise 'widgets_list are not of type Toolbox:WidgetList' unless widgets_list.is_a? Toolbox::WidgetList
  cond_template = []
  widgets_list.widgets.each do |w|
    table = w.model_name.tableize
    col_name = w.name
    a = col_name.to_s.split('.')
    if a.length > 1
      table = a[-2].tableize
      col_name = a[-1]
    end
    cond_template << "#{table}.#{col_name} like ? "
  end
  cond_template = '(' + cond_template.join(' or ') + ')'
  cond = Array.new
  cond.push('')
  filter.squeeze(' ').split(' ').each do |text|
    text = '%' + text + '%'
    cond[0] += ' and ' if !cond[0].empty?
    cond[0] += cond_template
    cond_template.count('?').times do cond.push(text) end
  end
  # in case of empty search text
  cond[0] = '1=1' if cond.length == 1
  cond
end

.setupObject

:nodoc:



8
9
10
11
12
# File 'lib/toolbox/searching.rb', line 8

def self.setup #:nodoc:
  ActionController::Base.send(:extend, ControllerClassMethods)
  ActionController::Base.send(:include, ControllerInstanceMethods)
  ActionView::Base.send(:include, HelperMethods)
end