截断 rails 中的句子?
Truncate sentences in rails?
我有一个助手可以用来截断 Rails 中的字符串,当我截断以句号结尾的句子时,它的效果很好。我应该如何修改代码以在句子以问号或感叹号结尾时也将其截断?
def smart_truncate(s, opts = {})
opts = {:words => 12}.merge(opts)
if opts[:sentences]
return s.split(/\.(\s|$)+/).reject{ |s| s.strip.empty? }[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 ? '... (more)' : '')
end
谢谢!!!
'Once upon a time in a world far far away'.truncate(27, separator: /\s/, ommission: "....")
这将 return "Once upon a time in a..."
如果您需要按字数截断,请使用新引入的 truncate_words
(自 Rails 4.2.2 起)
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
哪个return
"And they found that many... (continued)"
我有一个助手可以用来截断 Rails 中的字符串,当我截断以句号结尾的句子时,它的效果很好。我应该如何修改代码以在句子以问号或感叹号结尾时也将其截断?
def smart_truncate(s, opts = {})
opts = {:words => 12}.merge(opts)
if opts[:sentences]
return s.split(/\.(\s|$)+/).reject{ |s| s.strip.empty? }[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 ? '... (more)' : '')
end
谢谢!!!
'Once upon a time in a world far far away'.truncate(27, separator: /\s/, ommission: "....")
这将 return "Once upon a time in a..."
如果您需要按字数截断,请使用新引入的 truncate_words
(自 Rails 4.2.2 起)
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
哪个return
"And they found that many... (continued)"