我想知道是否有一个插件可以实现某种智能截断。我需要以一个单词或一个句子的精度来截断我的文本。
例如:
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.或
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 ...发布于 2009-08-18 13:20:16
我还没有见过这样的插件,但有一个similar question可以作为库或助手函数的基础。
您显示函数的方式似乎将其作为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..."发布于 2010-10-08 16:51:53
这将根据指定的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发布于 2013-08-06 15:56:47
gem truncate_html可以完成这项工作。它还可以跳过HTML片段-这可能非常有用-并提供自定义单词边界正则表达式的可能性。此外,所有参数的默认值都可以配置,例如在您的config/environment.rb中。
示例:
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>https://stackoverflow.com/questions/1293573
复制相似问题