Read more

Heads up: Rails offers two similar means for text truncation

Dominik Schöler
June 13, 2018Software engineer at makandra GmbH

Rails defines a #truncate helper as well as a method String#truncate.

= truncate("my string", length: 5)
= "my string".truncate(5)
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Both are really similar; in fact, the helper invokes the method and improves it with two niceties: support for passing a block (which could e.g. render a "read on" link), and html_safe knowledge.

Prefer the truncate() helper

Warning: truncate() calls html_safe if you're not escaping. FWIW, an HTML string may easily become invalid when truncated, e.g. when a closing tag gets chopped off.

However, when the input string is "fully html safe", i.e. contains no HTML, the truncated string should be html_safe to avoid escaping regular characters during rendering. A real-world example is a double quote (") that would be rendered as &quot when the string is escaped.

To mitigate this, use the helper with escape: false:

# Only pass escape:false when you're sure a truncated string is still html_safe
= truncate("my string", length: 5, escape: false)
Posted by Dominik Schöler to makandra dev (2018-06-13 14:59)