3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

shortenedされたURLを展開する

Last updated at Posted at 2012-09-19

bit.lyやow.ly、t.coと言った短縮URLは便利なのですが、データとして取り扱うと同一なのに違うモノとして扱われるので鬱陶しかったりします。なので展開します。

extend_url
require 'open-uri'
require 'net/http'

url = "http://t.co/hoge"
ary = ["bit.ly", "ow.ly", "goo.gl", "j.mp", "t.co", "youtu.be"]
uri = URI.parse(url)
host = uri.host
while ary.any? { |val| val == host }
  uri = Net::HTTP.new(uri.host, uri.port).get(uri.path).header['location']
  uri = URI.parse(uri)
  host = uri.host
end

展開したURLが短縮URLである場合(t.co/*** → ow.ly/***とか)もあるので、while文で配列とマッチする限りはリピートさせてます。
aryに短縮URLサービスのhostを追加していけば対応できるので楽なのですが、もっと美しい解決法もありそうだな、とも思います。
あと{ |val| val == host }的なことをする時にvalって語の選択としてどうなんだろ…とかも思いました。

gemでmoski / url_expanderもあるんですが、短縮URL系のサービスは山ほどあるのでAPIを管理しきれるのかな…と言う風に感じてこっちにしてみました。まぁ主に使われる物だけ対応すれば良いので大丈夫なんでしょうけど。

こんなのもあるよ!とかあったらコメントお願いします。

参考:
Ruby: expand shorten urls the hard way

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?