Search code examples
ruby-on-railsrubyransack

How to truncate the text and highlight search keyword when the text is too long


I am using Ransack gem for a search functionality in my Rails application. I am highlighting the search keyword param : params[:search] in the search results. I have successfully done it with the highlight helper method

<%= highlight(@description.slice(0..50), params[:search]) %>

This works fine if the keyword occurs between the first 50 character of @description

But if the keyword occurs after 50 characters, how is it possible to highlight it with limiting the number of characters.

I have found a solution myself and added it as the answer. Is there any other efficient solution?


Solution

  • excerpt helper method can be used to extract the text that matches the first instance of a phrase.

    <%= highlight(excerpt(@description, params[:search], radius: 50), params[:search]) %>
    

    More details on TextHelper: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html