bit.lyの展開

30分プログラム、その578。新しくTwitterが採用した、URL短縮サービスbit.lyを展開してみよう。

APIを使うのはAPIキーが必要になったりして面倒だなー、と思いながらtinyurlの展開をしてるtig.rbのコードを読んでみた。そしたら、実に賢いことしてた。

def untinyurl(text)
  text.gsub(%r|http://tinyurl.com/[0-9a-z=]+|i) {|m|
    uri = URI(m)
    Net::HTTP.start(uri.host, uri.port) {|http|
      http.head(uri.request_uri)["Location"]
    }
 }
end

実際にURLにアクセスして、Locationヘッダを見てる。すげーな、これ。これなら、大抵の短縮URLサービスが展開できるじゃないか。

というわけで、これをまるまるパクってみた。

使い方

bit.lyの展開を目指してたけど、他のも展開できます。

$ ruby expand.rb http://bit.ly/7jmys
http://www.youtube.com/watch?v=xnq0PLldu1s

$ ruby expand.rb http://is.gd/sAot
http://os2009.okaya.ma/

ソースコード

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# expand.rb -
#
# Copyright(C) 2009 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2009/05/08 22:17:00
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

def expand(s)
  uri = URI(s)
  Net::HTTP.start(uri.host, uri.port) {|http|
    http.head(uri.request_uri)["Location"]
  }
end

ARGV.each {|s|
  puts expand(s)
}