Skip to content

Instantly share code, notes, and snippets.

@mehulkar
Created June 27, 2013 01:07
Show Gist options
  • Save mehulkar/5873197 to your computer and use it in GitHub Desktop.
Save mehulkar/5873197 to your computer and use it in GitHub Desktop.
truncating and adding ellipsis to string in ruby
# 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