Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting characters/words in view - ruby on rails

I am displaying recent comments on the home page of a very simple blog application I am building in Ruby on Rails. I want to limit the number of characters that are displayed from the 'body' column of the comments table. I am assuming I can just add something to the end of the code for <%=h comment.body %> but I don't know what that would be yet as I am new to both Ruby and Rails.

Here is the code I have in the /views/posts/index.html.erb file:

<% Comment.find(:all, :order => 'created_at DESC', :limit => 5).each do |comment| -%>
    <p>
        <%=h comment.name %> commented on 
        <%= link_to h(comment.post.title), comment.post %><br/>
        <%=h comment.body %>
        <i> <%= time_ago_in_words(comment.created_at) %> ago</i>
    </p>
    <% end -%>
like image 837
bgadoci Avatar asked Apr 13 '10 20:04

bgadoci


4 Answers

Try the truncate view helper

<%=h truncate(comment.body, :length => 80) %>
like image 180
Corey Avatar answered Nov 20 '22 14:11

Corey


I just found another way (if you don't want to add the "...")

<%= comment.body.first(80) %>

As said in the RoR API for String:

first(limit = 1)

Returns the first character. If a limit is supplied, returns a substring from the beginning of the string until it reaches the limit value. If the given limit is greater than or equal to the string length, returns self.

comment = "1234567890"

comment.first(5)
# => "12345"

comment.first(10)
# => "1234567890"

comment.first(15)
# => "1234567890"
like image 42
maxhm10 Avatar answered Nov 20 '22 16:11

maxhm10


If you are using rails 4.2 or above then you can use truncate_words method.

For example:
"In a world where everything is awesome".truncate_words(3)

Output: "In a world..."

like image 7
jain77 Avatar answered Nov 20 '22 16:11

jain77


You can also use the truncate method if you want to limit the number of characters.

<%= "#{message.truncate(charcount)}" %>
like image 1
xxx Avatar answered Nov 20 '22 15:11

xxx