13

1) I want to auto wrap a text by words so that each line does not exceed 56 characters. Is there a method for doing this, or do I need to roll my own?

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

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.

2) I want to indent the text by 4 spaces so that:

<%= @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.
sawa
  • 165,429
  • 45
  • 277
  • 381
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118

2 Answers2

20

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.

jerodsanto
  • 9,726
  • 8
  • 29
  • 23
  • As a side-note, this is part of part of ActionView::Helpers::TextHelper -- [docs](https://apidock.com/rails/ActionView/Helpers/TextHelper/word_wrap) -- and can be (with a little effort) mixed in to non-rails projects if desired. – lindes Apr 16 '21 at 03:54
9

Perhaps word_wrap helper can help you.

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

sawa
  • 165,429
  • 45
  • 277
  • 381
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364