How can I center truncate a string?
If you want a certain fixed length irrespective of the length of the string, you can use Rails #truncate
:
s.truncate(100, omission: "...#{s.last(50)}")
Here is a modified version of Mike Woodhouse's answer. It takes 2 optional params: a minimum length for the the string to be ellipsisized and the edge length.
class String
def ellipsisize(minimum_length=4,edge_length=3)
return self if self.length < minimum_length or self.length <= edge_length*2
edge = '.'*edge_length
mid_length = self.length - edge_length*2
gsub(/(#{edge}).{#{mid_length},}(#{edge})/, '\1...\2')
end
end
"abc".ellipsisize #=> "abc"
"abcdefghi".ellipsisize #=> "abcdefghi"
"abcdefghij".ellipsisize #=> "abc...hij"
"abcdefghij".ellipsisize(4,4) #=> "abcd...ghij"
"Testing all paramas and checking them!".ellipsisize(6,5) #=> "Testi...them!"