Class: ActionController::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_autocomplete.rb

Overview

see Readme for details

Class Method Summary collapse

Class Method Details

.autocomplete_for(object, method, options = {}, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/simple_autocomplete.rb', line 7

def self.autocomplete_for(object, method, options = {}, &block)
  # do not modify options with e.g. delete
  # https://github.com/grosser/simple_auto_complete/pull/6
  define_method("autocomplete_for_#{object}_#{method}") do
    methods = options[:match] || [*method]
    condition = methods.map{|m| "LOWER(#{m}) LIKE ?"} * " OR "
    values = methods.map{|m| "%#{params[:q].to_s.downcase}%"}
    conditions = [condition, *values]

    model = object.to_s.camelize.constantize
    find_options = {
      :conditions => conditions,
      :order => "#{methods.first} ASC",
      :limit => 10
      }.merge!(options.except(:match))

    @items = model.scoped(find_options)

    out = if block_given?
      instance_exec @items, &block
    else
      %Q[<%= @items.map {|item| h(item.#{methods.first})}.uniq.join("\n")%>]
    end
    render :inline => out
  end
end