The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Google-like Search Results Helper

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Matthias Georgi

Posts: 54
Nickname: georgi
Registered: Apr, 2007

Matthias Georgi is a Ruby on Rails freelancer.
Google-like Search Results Helper Posted: May 10, 2007 6:11 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Matthias Georgi.
Original Post: Google-like Search Results Helper
Feed Title: Matthias Georgi
Feed URL: http://feeds.feedburner.com/matthias-georgi?format=xml
Feed Description: Webdev, Gamedev and Interaction Design.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Matthias Georgi
Latest Posts From Matthias Georgi

Advertisement

Representing your search results in a user-friendly way is a common task among web developers. Google's approach is dead simple but really effective. The matching text is highlighted and shown with its context. This can be implemented in less than 20 lines of code which you can include into you helper:

def highlight_text(text, words)
  tokens = strip_tags(text).split
  sections = []
  words.each do |word|
    word = word.downcase
    tokens.each_with_index do |token, i|
      if token.downcase.include? word
        section = tokens[i-10, 20].join(' ')
        words.each do |word|
          section = highlight section, word
        end
        sections << section + ' ... '
        break if sections.size > 3          
      end
    end
  end
  sections.join
end

First we remove the html tags of the text and split the text into tokens. Then we iterate over the search words and for each matching token we generate a section, which contains the highlighted word. This is done until we hav at least 4 sections, which are finally joined and ready to be included into the search result template.

Read: Google-like Search Results Helper

Topic: Introducing Boxcar... coming soon to a train station near you! Previous Topic   Next Topic Topic: What Went Wrong with my Javascript?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use