Mr. Demetrius Michael
Mr. Demetrius Michael

Reputation: 2406

Ruby: expand shorten urls the hard way

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.

Upvotes: 5

Views: 1065

Answers (1)

abdollar
abdollar

Reputation: 3415

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"

Upvotes: 7

Related Questions