截断只允许两个可选参数,:omission
并且:separator
. 您可以通过以下 truncate 代码看到它仅设置为使用字符串 for :separator
:
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 38
def truncate(length, options = {})
text = self.dup
options[:omission] ||= "..."
length_with_room_for_omission = length - options[:omission].mb_chars.length
chars = text.mb_chars
stop = options[:separator] ? (chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
(chars.length > length ? chars[0...stop] + options[:omission] : text).to_s
end
话虽如此,您应该能够通过以下方式完成您想要实现的目标(如果我正确理解情况)(首先将换行符和诸如此类的东西切换到空格):
truncate(content.gsub(/\s/i, ' '), :length=>60, :separator=>' ')
如果这太简单了,您可能会想出您想要的内容,只需对官方truncate()
代码进行相当简单的修改......