Created
November 8, 2012 21:39
-
-
Save joshuaswilcox/4041859 to your computer and use it in GitHub Desktop.
Trims ruby string to set length maintaining full words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def desc_trim | |
@string = self.description.to_s | |
@max = 120 | |
if @string | |
if @string.size > @max | |
@words = @string.split(' ') | |
@end = "..." | |
@output = '' | |
i = 0 | |
@words.each_with_index do |w, i| | |
@length = @output.size + w.size | |
begin | |
if @length < @max | |
@output = @output + " " + w | |
end | |
rescue | |
puts "!!!longer!!!" | |
end | |
end | |
@output = @output + @end.to_s | |
else | |
@output = @string | |
end | |
@output | |
else | |
'' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment