[Ruby] [For those who create portfolios] How to omit the character string

1 minute read

When creating a portfolio, I thought that I wanted to omit the long sentence and display “Read more” or “…”, so I will summarize here.

Conclusion

Use the truncate method.

How to use

There are two types of truncate.

String

string.rb


 "Spring is Akebono. It's about to turn white, on the mountains, a little light, and a thin stream of purple clouds.".truncate(30) %>
 # "Spring is Akebono. Finally, on the edge of the whitening mountain, a little light,..."

| Options | Description | Default | |:——- | :——- |:——-| |:omission| Character string to be added after the omitted character string |…| |:separator| Separator. Make sure that the character string is not cut off halfway. I can’t do it in Japanese. | None |

With these,

string.rb


"Spring is Akebono. Yay, it's turning white, the mountains are shining a little, and the clouds of purple fluttering are thin.".truncate(30, omission:'... Read more', separator:'')
# "Spring is Akebono. It's about to turn white, and there are a few... Read More"

TextHelper

texthelper.rb


truncate ("Spring is Akebono. It's about to turn white, on the mountainside, a little light, a thin cloud of purple fluttering.")
# "Spring is Akebono. Finally, on the edge of the whitening mountain, a little light,..."

| Options | Description | Default | |:——–|:——|:——-| |:length | Character string length before omission | 30 | |:omission | A string that follows the omitted string | … | |:separator | Separator. Make sure that the character string is not cut off halfway. I can’t do it in Japanese. | None | |:escape |HTML escape (if you specify false, it will not be escaped) |true |

Actual result

I used it to display the content of the person who posted.

<%= truncate(@post.content, length: 50) do %>
  <p><%= link_to'Read more', @post %></p>
<% end %>

Screenshot 2020-07-20 19.03.45.png When you enter the weekly report, the post is displayed on the right side, after displaying 50 characters of the post content, you can jump to the details with the link to read more.

reference

https://apidock.com/rails/String/truncate https://apidock.com/rails/ActionView/Helpers/TextHelper/truncate