module ActionView::Helpers::TextHelper
def truncate(text, options = {}, &block)
truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
# => "
Once upon a time in a wo..."
truncate("
Once upon a time in a world far far away
", escape: false)# => "<p>Once upon a time in a wo..."
truncate("
Once upon a time in a world far far away
")# => "And they f... (continued)"
truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
# => "Once upon a..."
truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a ti..."
truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a time in a world..."
truncate("Once upon a time in a world far far away")
may produce invalid HTML (such as unbalanced or incomplete tags).
+false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
The result is marked as HTML-safe, but it is escaped by default, unless :escape is
Pass a block if you want to show extra content when the text is truncated.
Pass a :separator to truncate +text+ at a natural break.
for a total length not exceeding :length.
(defaults to 30). The last characters will be replaced with the :omission (defaults to "...")
Truncates a given +text+ after a given :length if +text+ is longer than :length
def truncate(text, options = {}, &block) if text length = options.fetch(:length, 30) content = text.truncate(length, options) content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content) content << capture(&block) if block_given? && text.length > length content end end