excerpt

If you’ve ever wanted to implement a search function in your Ruby on Rails application, you might want to read up on excerpt. Built into ActionView, this helper function lets you extract an excerpt from text that matches a phrase.

This can allow you to show context along with the search results to a user, which is definitely better than just getting the page title.

excerpt(text, phrase, options = {})

excerpt('This is an example', 'an', radius:5)
# => ...s is an exam...

Through use of the provided options, you can control how much is seen on either side of the match.

# break on whitespace between words.
separator: ‘ ‘

# return 8 items on either side of the phrase
radius: 8

Let’s take a look at a more complex example to see how it might be helpful to use for a search results page.

excerpt('Today we had a very beautiful sunrise', 'very', separator: ' ', radius: 2
# => ...had a very beautiful sunrise

As you would expect, the excerpt grabbed the 2 words before and after the matched phrase. Since sunrise is the last word, you don’t see the ellipsis at the end. This gives you the context to know if that result is the one you are really after.

Hopefully you can use this to provide better context for your users.

For full documentation, see the docs.

Leave a Reply

Your email address will not be published. Required fields are marked *