Sha256: b70690bda4b944b6614237fbb2eb6d77847a399dff8a43bf4569b99480d595f1

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 KB

Contents

module Autocomplete
  def self.included(base)
    base.extend(ClassMethods)
  end

  # Inspired on DHH's autocomplete plugin
  # 
  # Usage:
  # 
  # class ProductsController < Admin::BaseController
  #   autocomplete :brand, :name
  # end
  #
  # This will magically generate an action autocomplete_brand_name, so, 
  # don't forget to add it on your routes file
  # 
  #   resources :products do
  #      get :autocomplete_brand_name, :on => :collection
  #   end
  #
  # Now, on your view, all you have to do is have a text field like:
  # 
  #   f.text_field :brand_name, :autocomplete => autocomplete_brand_name_products_path
  #
  # That's it!
  #
  #
  module ClassMethods
    def autocomplete(object, method, options = {})
      limit = options[:limit] || 10
      order = options[:order] || "#{method} ASC"

      define_method("autocomplete_#{object}_#{method}") do
        unless params[:term] && params[:term].empty?
          items = object.to_s.camelize.constantize.where(["LOWER(#{method}) LIKE ?", "#{params[:term]}%"]).limit(limit).order(order)
        else
          items = {}
        end

        render :json => json_for_autocomplete(items, method)
      end
    end
  end

  private
  def json_for_autocomplete(items, method)
    items.collect {|i| {"id" => i.id, "label" => i[method], "value" => i[method]}}
  end
end

class ActionController::Base
  include Autocomplete
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rails3-jquery-autocomplete-0.1.2 lib/autocomplete.rb
rails3-jquery-autocomplete-0.1.1 lib/autocomplete.rb
rails3-jquery-autocomplete-0.1.0 lib/autocomplete.rb