Created
June 27, 2013 01:07
-
-
Save mehulkar/5873197 to your computer and use it in GitHub Desktop.
truncating and adding ellipsis to string in ruby
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
# this is probably a fairly common use case | |
# but there must be a more elegant solution? | |
# shortened_url returns a bit.ly link or nil in development | |
class Post | |
def tweet_text | |
link_length = shortened_url ? shortened_url.length : "" | |
separator = "-" | |
available_chars = link_length - separator.length | |
str = if available_chars < title.length | |
title.first(available_chars) | |
else | |
title.first(available_chars - 3) + "..." | |
end | |
return "#{str} #{separator} #{shortened_url}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment