views:

201

answers:

2

I am building a comment notification system in Rails and I am trying to render user provided comments in a plain text email.

When I render the comment, I want to auto wrap the lines when 56 characters are reached. Obviously I don't want to split words.

Is there a function in Ruby or RoR for doing this, or do I need to roll my own?

Quick Illustration

@comment_text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

Then in my view:

<%= @comment_text.cool_string_function( 56 ) %>

Would render:

Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et 
dolore magna aliqua.

One more problem:

The last thing I want to tackle (if you can answer this, great. If not, the first part is the really important thing) is that I want to indent their comment by 4 spaces or so:

<%= @comment_text.cool_string_function( {:width => 56, :indent => 4} ) %>

Would render:

    Lorem ipsum dolor sit amet, consectetur adipisicing
    elit, sed do eiusmod tempor incididunt ut labore et 
    dolore magna aliqua.
+1  A: 

Perhaps word_wrap helper can help you.

To indent the text you can replace \n with \n (newline + 4 spaces).

Simone Carletti
+1 Thanks for your time and the answer. This looks like exactly what I want.
Doug Neiner
+2  A: 

I believe the function you are looking for is word_wrap. Something like this should work:

<%= word_wrap @comment_text, :line_width => 56 %>

You can combine that with gsub to get the indentation you desire:

<%= word_wrap(@comment_text, :line_width => 52).gsub("\n", "\n    ") %>

But you should probably move that into a helper method to keep your view clean.

sant0sk1
+1 Thank you for your answer and the examples!
Doug Neiner