Rails 6 adds String#truncate_bytes to truncate a string to a maximum bytesize without breaking multibyte characters or grapheme clusters like 👩👩👦👦.
Previously to truncate strings with multibyte characters, we had to first convert strings to mb_chars
We could achieve truncating such strings like:
mb_chars.limit is relatively slower
and we have to do a special conversion to
mb_chars first on String.
String#truncate_bytes provides a faster and easier alternative.
We can now achieve the same like so:
Note how in the last example,
truncate_bytes tries to preserves the grapheme cluster
and treats it as a single unit.
Instead of treating it as 3 separate characters’ bytes merged together(“👩” + “❤” + “👩” = “👩❤️👩”),
it ignores the cluster as a whole and truncates the cluster.
String#truncate_bytes takes an optional
omission argument to end the string with,
which defaults to “…”.
Apart from being a convenient method available on
String#truncate_bytes is also much faster compared to