Skip to content

Instantly share code, notes, and snippets.

@nu7hatch
Created October 15, 2010 08:56
Show Gist options
  • Save nu7hatch/627878 to your computer and use it in GitHub Desktop.
Save nu7hatch/627878 to your computer and use it in GitHub Desktop.
Simple links shortening
# It produces shorten version of given url.
#
# p truncate_url("http://example.com/hello.html")
# p truncate_url("http://example.com/yada-yada-yada/foobar/hello.html", :length => 40)
#
# will produce:
#
# "http://example.com/hello.html"
# "http://example.com/...foobar/hello.html"
def truncate_url(url, options={})
options = { :length => 50, :ommision => "..." }.merge(options)
if url && url.size > options[:length]
proto, domain, *path = url.split(/\/+/)
length = options[:length]-(proto.size+domain.size+4+options[:ommision].size)
path = [options[:ommision], path.join("/")[-length, length]].join
url = "#{proto}//#{domain}/#{path}"
end
return url
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment