Skip to content


Getting TinyUrl’s in Rails

If you have used twitter I am sure you have noticed that if you post a long url in your update it gets turned in to a tinyurl for you. This is really cool functionality and I have created a helper in rails to do it for me.

First, let’s talk about how you get a tinyurl. Tinyurl has a really simple api that you can call that will return a tiny url. It is rediculous how simple it is. You just call this url with a GET: http://tinyurl.comapi-create.php?url=http://example.com

The returned page will be a single line with the tinyurl equivalent. It is that simple. Now on to the rails part.

In your application.rb helper you would add this:

require ‘net/http’
require ‘uri’

def tinyfy(newurl)
   url = URI.parse(‘http://tinyurl.com/’)
   res = Net::HTTP.start(url.host, url.port) {|http|
   http.get(‘/api-create.php?url=’ + newurl)
   }
   if res.body.empty?
      #tinyurl is not responding properly… Return the original url
      return newurl
   else
      return res.body
   end
end

Now if you call the tinyfy method in your app, let’s say in your view, with the url you want to tinyurlify as the parameter the return will be the tinyurl. I take this one step further and have the tinyfy method make the url a link by adding the ‘a’ tags in the method like so:

require ‘net/http’
require ‘uri’

def tinyfy(newurl)
   url = URI.parse(‘http://tinyurl.com/’)
   res = Net::HTTP.start(url.host, url.port) {|http|
   http.get(‘/api-create.php?url=’ + newurl)
   }
   if res.body.empty?
      #tinyurl is not responding properly… Return the original url
      return ‘<a href=’ + newurl + ‘>’ + newurl + ‘</a>’
   else
      return ‘<a href=’ + res.body + ‘>’ + res.body + ‘</a>’
   end
end

That will return a nice linked tinyurl in your view. That is all there is to it.

Posted in Rails, Tech.

One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Thanks very much. That was really fine of you to share this! I’m still learning Rails, and this neatly shows the concept of using other services behind the scenes.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.