Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: expand shorten urls the hard way

Tags:

url

ruby

Is there a way to open URLS in ruby and output the re-directed url: ie convert http://bit.ly/l223ue to http://paper.li/CoyDavidsonCRE/1309121465

I find that there are more url shortener services than gems can keep up with, so I'm asking for the hard -but robust- way, instead of using a gem that connects to some API.

like image 333
Mr. Demetrius Michael Avatar asked Feb 16 '12 05:02

Mr. Demetrius Michael


1 Answers

Here is a lengthen method

This has very little error handling but it might help you get started. You could wrap lengthen with a begin rescue block that returns nil or attempt to retry it later. Not sure what you are trying to build but hope it helps.

require 'uri'
require 'net/http'

def lengthen(url)
  uri = URI(url)
  Net::HTTP.new(uri.host, uri.port).get(uri.path).header['location']
end


irb(main):008:0> lengthen('http://bit.ly/l223ue')
=> "http://paper.li/CoyDavidsonCRE/1309121465"
like image 80
abdollar Avatar answered Oct 24 '22 17:10

abdollar