Created
October 15, 2010 08:56
-
-
Save nu7hatch/627878 to your computer and use it in GitHub Desktop.
Simple links shortening
This file contains hidden or 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
# 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