首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails:智能文本截断

Rails:智能文本截断
EN

Stack Overflow用户
提问于 2009-08-18 12:41:41
回答 5查看 4.7K关注 0票数 10

我想知道是否有一个插件可以实现某种智能截断。我需要以一个单词或一个句子的精度来截断我的文本。

例如:

代码语言:javascript
复制
Post.my_message.smart_truncate(
    "Once upon a time in a world far far away. And they found that many people
     were sleeping better.", :sentences => 1)
# => Once upon a time in a world far far away.

代码语言:javascript
复制
Post.my_message.smart_truncate(
    "Once upon a time in a world far far away. And they found that many people
     were sleeping better.", :words => 12)
# => Once upon a time in a world far far away. And they ...
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-08-18 13:20:16

我还没有见过这样的插件,但有一个similar question可以作为库或助手函数的基础。

您显示函数的方式似乎将其作为String的扩展:除非您真的希望能够在视图之外执行此操作,否则我倾向于使用application_helper.rb中的函数。也许是这样的吧?

代码语言:javascript
复制
module ApplicationHelper

  def smart_truncate(s, opts = {})
    opts = {:words => 12}.merge(opts)
    if opts[:sentences]
      return s.split(/\.(\s|$)+/)[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '.'
    end
    a = s.split(/\s/) # or /[ ]+/ to only split on spaces
    n = opts[:words]
    a[0...n].join(' ') + (a.size > n ? '...' : '')
  end
end

smart_truncate("a b c. d e f. g h i.", :sentences => 2) #=> "a b c. d e f."
smart_truncate("apple blueberry cherry plum", :words => 3) #=> "apple blueberry cherry..."
票数 20
EN

Stack Overflow用户

发布于 2010-10-08 16:51:53

这将根据指定的char_limit长度在单词边界处截断。所以它不会在奇怪的地方截断句子。

代码语言:javascript
复制
def smart_truncate(text, char_limit)
    size = 0
    text.split().reject do |token|
      size += token.size() + 1
      size > char_limit
    end.join(' ') + ( text.size() > char_limit ? ' ' + '...' : '' )
end
票数 8
EN

Stack Overflow用户

发布于 2013-08-06 15:56:47

gem truncate_html可以完成这项工作。它还可以跳过HTML片段-这可能非常有用-并提供自定义单词边界正则表达式的可能性。此外,所有参数的默认值都可以配置,例如在您的config/environment.rb中。

示例:

代码语言:javascript
复制
some_html = '<ul><li><a href="http://whatever">This is a link</a></li></ul>'

truncate_html(some_html, :length => 15, :omission => '...(continued)')
=> <ul><li><a href="http://whatever">This...(continued)</a></li></ul>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1293573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档