Ruby on Rails ActiveSupport Core Extensions: String Filters


Example

String#squish

Returns a version of the given string without leading or trailing whitespace, and combines all consecutive whitespace in the interior to single spaces. Destructive version squish! operates directly on the string instance.

Handles both ASCII and Unicode whitespace.

%{ Multi-line
   string }.squish                   # => "Multi-line string"
" foo   bar    \n   \t   boo".squish # => "foo bar boo"

String#remove

Returns a new string with all occurrences of the patterns removed. Destructive version remove! operates directly on the given string.

str = "foo bar test"
str.remove(" test")                 # => "foo bar"
str.remove(" test", /bar/)          # => "foo "

String#truncate

Returns a copy of a given string truncated at a given length if the string is longer than the length.

'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

Pass a string or regexp :separator to truncate at a natural break

'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# => "Once upon a time in a..."

'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# => "Once upon a time in a..."

String#truncate_words

Returns a string truncated after a given number of words.

'Once upon a time in a world far far away'.truncate_words(4)
# => "Once upon a time..."

Pass a string or regexp to specify a different separator of words

'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>')
# => "Once<br>upon<br>a<br>time<br>in..."

The last characters will be replaced with the :omission string (defaults to "...")

'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
# => "And they found that many... (continued)"

String#strip_heredoc

Strips indentation in heredocs. Looks for the least-indented non-empty line and removes that amount of leading whitespace.

if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end

the user would see

This command does such and such.

Supported options are:
-h         This message
...