Rails 6 adds String#truncate_bytes to truncate a string to a maximum bytesize without breaking multibyte characters or grapheme clusters like π©βπ©βπ¦βπ¦.
Before
Previously to truncate strings with multibyte characters, we had to first convert strings to mb_chars
We could achieve truncating such strings like:
String#truncate_bytes
Using 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
,
String#truncate_bytes
is also much faster compared to mb_chars.limit
: