Truncate只允許兩個可選參數,:omission
和: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
有了這個說,你應該能夠做到你想做到什麼(如果我:你可以通過截斷下面的代碼,它是隻設置了一個字符串,攜手合作,:separator
見像這樣的東西理解正確的情況下)(開關換行符和諸如此類的東西的空間,在前):
truncate(content.gsub(/\s/i, ' '), :length=>60, :separator=>' ')
如果這是太簡單了,你也許可以想出你想要什麼,有一個非常簡單的修改官方truncate()
代碼...
您可以擴展「我的主要目標是檢查\ n(輸入/換行)」嗎?我得到了「檢查」部分,但是最後你會在哪裏添加它? –
增加了細節;現在更清楚了嗎? – dmonopoly
我想我得到你要去的地方... –