Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Truncate to a specific string

Clarification: The creator of the post should be able to decide when the truncation should happen.

I implemented a Wordpress like [---MORE---] functionality in my blog with 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 post body will display everything up to (but without) the [---MORE---] tag.

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

And in the show view everything from the post body will be displayed except the [---MORE---] tag.

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

This solution currently works for me without any problems. Since I am still a beginner in programming I am constantly wondering if there is a more elegant way to accomplish this.

How would you do this?

Thanks for your time.


This is the updated version:

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

...and in the show view:

# show.html.erb
<%=raw (@post.rendered_body).gsub("[---MORE---]", '') %>
like image 669
therod Avatar asked Feb 25 '23 02:02

therod


1 Answers

I would use just simply truncate, it has all of the options you need.

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

Update

After sawing the comments, and digging a bit the documentation it seems that the :separator does the work.

From the doc:

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

For referenece see the docs

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

On the show page you have to use gsub

like image 150
dombesz Avatar answered Mar 07 '23 03:03

dombesz