【问题标题】:Truncate sentences in rails?在rails中截断句子?
【发布时间】:2016-04-06 22:07:00
【问题描述】:

我有一个帮助器,用于在 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

谢谢!!!

【问题讨论】:

  • 任何不使用这个的理由:api.rubyonrails.org/classes/ActionView/Helpers/…
  • 你有没有考虑使用 Rails 提供的truncate
  • 我考虑过使用 truncate 但它不适合我的需要。我正在使用这个助手来预览内容而不会破坏它(太长)并且显示整个句子是我已经确定的。
  • 这就是:separator 选项的用途。

标签: ruby-on-rails ruby string truncate


【解决方案1】:

你有truncate method

'Once upon a time in a world far far away'.truncate(27, separator: /\s/, ommission: "....")

这将返回"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)')

返回

"And they found that many... (continued)"

【讨论】:

    猜你喜欢
    • 2015-11-24
    • 2011-05-01
    • 2013-08-04
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2011-09-10
    相关资源
    最近更新 更多