Rails:智能文本截断

gmi*_*ile 10 ruby text truncate ruby-on-rails

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

例如:

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.
Run Code Online (Sandbox Code Playgroud)

要么

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 ...
Run Code Online (Sandbox Code Playgroud)

Mik*_*use 20

我还没有看过这样的插件,但是有一个类似的问题可以作为lib或helper函数的基础.

你展示函数的方式似乎把它作为String的扩展:除非你真的希望能够在视图之外做到这一点,否则我倾向于选择函数application_helper.rb.也许是这样的事情?

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..."
Run Code Online (Sandbox Code Playgroud)


小智 8

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

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
Run Code Online (Sandbox Code Playgroud)

  • 这不包括字符数中的空格.如果你想考虑空格,它的大小应该是+ = token.size + 1. (2认同)