views:

90

answers:

1

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 -%>
+6  A: 

Try the truncate view helper

<%=h truncate(comment.body, :length => 80) %>
Corey
Thats perfect thank you.
bgadoci
Just curious (not a Rails user): would this also work?<%=h comment.body[0, 80]+"..." %>
steenslag
That's pretty much what truncate does underneath, but it also checks the length to know if to add the '...' at the end
Corey
Just wanted to add that truncate is not multi-byte safe (ruby 1.8, rails 2.3.5, not sure about ruby 1.9). It truncates at the specified byte and if you have a unicode string the output will be shorter (less characters than the length specified). You could also end up with a broken character at the end. Of course, there's nothing to worry about if you use ASCII or any othern 8-bit character encoding.
Teoulas