Ruby on Rails - truncating a specific line

Explanation: The creator of the message must be able to decide when the truncation will occur.

My blog has a Wordpress feature, such as [--- MORE ---], with the following helper function:

# application_helper.rb

def more_split(content)
split = content.split("[---MORE---]")
split.first
end

def remove_more_tag(content)
content.sub("[---MORE---]", '')
end

In the index view, the message body will display everything before (but without) the [--- MORE ---] tag.

# index.html.erb
<%= raw more_split(post.rendered_body) %>

And in the show view everything will be displayed, starting with the body of the message, except for the tag [--- MORE ---].

# show.html.erb
<%=raw remove_more_tag(@post.rendered_body) %>

This solution currently works for me without a problem. Since I'm still new to programming, I am constantly wondering if there is a more elegant way to accomplish this .

How do you do this?

Thank you for your time.


This is an updated version:

# index.html.erb
<%=raw truncate(post.rendered_body,  
                :length => 0, 
                :separator => '[---MORE---]', 
                :omission => link_to( "Continued...",post)) %>

... and in view view:

# show.html.erb
<%=raw (@post.rendered_body).gsub("[---MORE---]", '') %>
+3
4

, .

truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
# => "And they f... (continued)"

, , , :separator .

:

Pass a :separator to truncate text at a natural break.

. docs

truncate(post.rendered_body, :separator => '[---MORE---]')

gsub

+7

, X . , :

<%= raw summarize(post.rendered_body, 250) %>

250 . , [--- MORE ---]. , , ... post.body.


( application_helper.rb):

def summarize(body, length)
return simple_format(truncate(body.gsub(/<\/?.*?>/,  ""), :length => length)).gsub(/<\/?.*?>/,  "")
end
0

,

def summarize(body, length)
    return simple_format = body[0..length]+'...'
end

s = summarize("to get the first n characters in your post. So, then you don't have to deal w/ splitting on the [---MORE---]  post.body.",20)


ruby-1.9.2-p290 :017 > s
=> "to get the first n ..." 
0

I need one that I can use in this ERB call pattern. This is a simple line:

<%= @page_info.user_name %>

I tried <%= truncate(@page_info.user_name, :length => -2)

But in fact, it repeats a long username twice or differently depending on the number. I just want to allow 10 characters of username to be shown.

0
source

Source: https://habr.com/ru/post/1792536/


All Articles