Posted 4 months ago. Visible to the public.

Heads up: Rails offers two similar means for text truncation

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

Copy
= truncate("my string", length: 5) = "my string".truncate(5)

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

The method knows nothing about html_safe and will always return an unsafe string. 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:

Copy
# Only pass escape:false when you're sure a truncated string is still html_safe = truncate("my string", length: 5, escape: false)

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
4 months ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more