Well I´m using it together with some ajax search from a database.
Here´s my code:
search_controller.rb
=======================
def live_search
$KCODE = 'latin1'
@code = $KCODE
a1 = "%"
a2 = "%"
@searchstring_name_temp = params[:searching]
@searchstring_name = @searchstring_name_temp.rstrip.gsub(" ", "%'
AND name LIKE '%")
@searchstring_sku_temp = params[:searching]
@searchstring_sku = @searchstring_sku_temp.rstrip.gsub(" ", "%' AND
sku LIKE '%")
@results = Product.find_by_sql("SELECT * FROM products WHERE name
LIKE'"+a1+@searchstring_name+a2+"' OR sku
LIKE'"+a1+@searchstring_sku+a2+"' order by name asc LIMIT 0,50;")
# @results = Product.find_by_sql
all, :conditions => [ "name LIKE
?", a1+@searchstring+a2], :limit => 50)
@number_match = @results.length
render
layout => false)
end
def highlight(text,search_string)
keywords = search_string.squeeze.strip.split(" ").compact.uniq
matcher = Regexp.new( '(' + keywords.join("|") + ')' )
highlighted = text.gsub(matcher) { |match| "<b>#{match}</b>" }
return highlighted
end
live_search.rb
================
<%= @searchstring %>
<% if @results.empty? %>
not found!
<% else %>
found <b><%= @number_match %></b> time(s)!<BR>
<% @text = "This is an example of the text."
@search = "example text" %>
<%= highlight(@text,@search) %>
<table width=600 cellspacing="3">
<td width="100"><h2>sku</td><td width="500"><h2><b>name</td>
<% @results.each do |row| %>
<tr>
<td>
<%= highlight(row.sku.capitalize,@searchstring_name_temp) %>
</td>
<td>
<%= highlight(row.name.capitalize,@searchstring_name_temp)
%>
</td>
<% end %>
</table>
<% end %>