Rails的辅助工具excerpt ,可以提取与某个短语相匹配的一大块文本,不管它在字符串的什么位置。
想象一下,你想显示一个与某个搜索词相匹配的电子邮件列表。

只需过滤掉你的记录,然后在邮件正文上使用excerpt 。
使用方法
下面是你的视图建立这个功能的样子。
<%= link_to email do %>
<div class="flex justify-between items-center">
<p class="text-sm font-medium text-gray-900">
<%= email.sender_name %>
</p>
<%= local_time_ago email.received_at %>
</div>
<p class="text-sm text-gray-700">
<%= email.subject %>
</p>
<p class="text-sm text-gray-500">
<%= excerpt(email.body.to_plain_text, params[:q], radius: 15) %>
</p>
<% end %>
一个技巧是,如果你使用ActionText ,请调用to_plain_text ,否则你可能会出现未封闭的HTML标签。一般来说,当你显示富文本的摘录时,你无论如何都不希望所有的格式化被应用。
为了获得额外的分数,请与Rails的高亮帮助器结合使用。
选项
@product.description = "A one-of-a-kind vintange DHH coffee mug signed by the man himself!"
excerpt(@product.description, "coffee", radius: 10)
=> "...tange DHH coffee mug signe..."
这个帮助器不区分大小写,可以接受字符串或Regex。
@product.description = "A one-of-a-kind vintange DHH coffee mug signed by the man himself!"
excerpt(@product.description, "COFFEE", radius: 10)
=> "...tange DHH coffee mug signe..."
excerpt(@product.description, /tea|coffee/, radius: 10)
=> "...tange DHH coffee mug signe..."
选项
你可以扩大 "半径"--或者说在匹配的周围有多少个字符被显示。默认是100 。
@product.description = "A one-of-a-kind vintange DHH coffee mug signed by the man himself!"
excerpt(@product.description, "coffee", radius: 5)
=> "...DHH coffee mug..."
excerpt(@product.description, "coffee", radius: 25)
=> "...e-of-a-kind vintange DHH coffee mug signed by the man hi..."
如果你需要把... 改成其他的东西,请使用omission 选项。
@product.description = "A one-of-a-kind vintange DHH coffee mug signed by the man himself!"
excerpt(@product.description, "coffee", radius: 10)
=> "...tange DHH coffee mug signe..."
excerpt(@product.description, "coffee", radius: 10, omission: "---")
=> "---tange DHH coffee mug signe---"
excerpt(@product.description, "coffee", radius: 10, omission: "<snip>")
=> "<snip>tange DHH coffee mug signe<snip>"
其他资源
Rails API 文档。TextHelper#excerpt
Rails API 文档。ActionText#to_plain_text