Cooler #truncate

  • Posted on March 04, 2011

The default Rails’ #truncate method is really useful when doing things with long reams of text. Recently I needed a version that grabbed at least :length characters, instead of at most. Basically, :boundary needed to be greedy and I wanted to be able to specify a regex instead of a string if the mood caught me.

Here’s my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def rtruncate(long_string, opts={})
  text = long_string.to_s.strip
  return "" if text == ""

  defaults = {
    :boundary => /\w*/,
    :length   => 30,
    :omission => "..."
  }  

  options = defaults.merge(opts)

  return text if text.length <= options[:length]

  result = text.scan(Regexp.new(".{#{ options[:length] }}#{ options[:boundary] }")).first
  result << options[:omission] unless result.size == text.size
  result  
end

> numbers = "one two three four five"
> rtruncate(numbers, :length => 10)

#=> "one two three..."

> rtruncate(numbers, :length => numbers.length - 1)
#=> "one two three four five"

Yay!