Does anybody have any code handy that center truncates a string in Ruby on Rails?
Something like this: Ex: "Hello World, how are you?" => "Hel...you?"
Does anybody have any code handy that center truncates a string in Ruby on Rails?
Something like this: Ex: "Hello World, how are you?" => "Hel...you?"
Since you didn't specify how many characters you want to truncate, I'll assume (from your example) that you want to truncate strings whose length is greater than six. You can then use something like this:
s = "Hello World, how are you?"
s = s[0, 3] + "..." + s[-3, 3] if s.length > 9
=> "Hel...ou?"
Just adapt the ranges if you need to truncate more characters.
How about a Regex version:
class String
def ellipsisize
gsub(/(...).{4,}(...)/, '\1...\2')
end
end
"abc".ellipsisize #=> "abc"
"abcdefghi".ellipsisize #=> "abcdefghi"
"abcdefghij".ellipsisize #=> "abc...hij"
EDIT: as suggested in the comments, parameterised length (and using a different Regex notation, just for the heck of it)
class String
def ellipsisize(len = 9)
len = 9 unless len > 9 # assumes minimum chars at each end = 3
gsub(%r{(...).{#{len-5},}(...)}, '\1...\2')
end
end
so...
"abcdefghij".ellipsisize #=> "abc...hij"
but we can also:
"abcdefghij".ellipsisize(10) #=> "abcdefghij"
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!"