1. Computing

ShortURL: Use ShortURL for Twitter

Shortening URLs

By

Most URL shortening services provide some kind of API, so software can use these services without interaction from the user. While you can use these APIs directly, which would require only a little bit of HTTP wizardry, you can also use the ShortURL gem. ShortURL provides an easy one-line interface to any number of URL shortening services.

Installing

ShortURL installs just as any other gem. It require no native extensions and relies on no other gems.

$ sudo gem install shorturl

Basic Use

The entire ShortURL library has a single method of interest, ShortURL.shorten. Simply give it a URL you want shortened and it returns a string with the shortened URL. It couldn't be any eaiser.

#!/usr/bin/env ruby
require 'rubygems'
require 'shorturl'

puts ShortURL.shorten('http://ruby.about.com')
$ ./shorten.rb
http://rubyurl.com/495J

Other Services

By default, ShortURL will use the rubyurl.com service. In addition to this service, ShortURL also works on a number of other services. The ShortURL.valid_services method returns a list of services ShortURL will work with.

#!/usr/bin/env ruby
require 'rubygems'
require 'shorturl'

puts ShortURL.valid_services
$ ./services.rb
shiturl
urltea
shorterlink
rubyurl
littlink
minilink
clipurl
metamark
lns
tinyurl
shortify
makeashorterlink
fyad
shorl
orz
skinnylink
d62
snipurl
moourl
linktrim

To use any of these services, just pass the name of the service as a label to the shorten method along with the URL to be shortened.

#!/usr/bin/env ruby
require 'rubygems'
require 'shorturl'

puts ShortURL.shorten('http://ruby.about.com', :lns)

Note that supporting any of these services is a moving target. Try the service you wish to use in IRB before using it in your scripts.

Command-line Program

ShortURL also provides a command-line interface to the ShortURL library. It's available from the shorturl command.

$ shorturl http://ruby.about.com
http://rubyurl.com/495J
See More About
  1. About.com
  2. Computing
  3. Ruby
  4. Gems
  5. ShortURL: Use ShortURL for Twitter

©2014 About.com. All rights reserved.