Saturday, February 21, 2009

String#bitruncate

And that's '"bi-truncate" not "bit-uncate".

What's it do?

"This is a test".bitruncate(:length => 6) ==> "Thi...est"
"This is a test".bitruncate(:elength => 6) ==> "...a test"

The default options are { :length => 30 } which will produce 15 characters from the front and 15 from the end, putting ... marks in the middle.

For rails, I put this in my lib/core_extensions.rb file.

class String
 #
 # Truncate from both ends of a string.  The :length parameter, which defaults
 # to 30, will return the first 15 and the last 15 characters from a string
 # if it is longer than 30 characters.  If it is shorter, the entire string
 # is returned.
 #
 # Another way to specify the front and back portions are with :flength and
 # :elength.  If you specify one of these but not the other then you will
 # not get the missing part.  e.g., :flength => 10 alone will return only
 # the first 10 charcters of the string.  This is the same as the standard
 # truncate(s, :length => 10) helper.
 #
 # If a :length parameter is provided it will override any other lengths
 # specified.
 #
 def bitruncate(options = {})
   maxlength = options[:length] || 0
   flength = options[:flength] || 0
   elength = options[:elength] || 0
   omission = options[:omission] || '...'

   if maxlength == 0 && flength == 0 && elength == 0
     maxlength = 30
    end
    if maxlength != 0
      flength = maxlength / 2
      elength = maxlength / 2
    end
    
    return self if length <= (flength + elength)
    
    front = ''
    back = ''
    if flength > 0
      front = self[0..(flength - 1)]
    end
    if elength > 0
      back = self[(length - elength)..(length)]
    end
    
    front + omission + back
 end
end

No comments:

Post a Comment