LoginSignup
11
9

More than 5 years have passed since last update.

Rubyで短縮URLを展開する

Posted at

HTTPレスポンスがリダイレクトであればLocationヘッダを読んでいます。
短縮URLがネストしている場合にも対応すべく、再帰的に処理しています。

require 'net/http'
require 'uri'

def expand_url(url)
  begin
    response = Net::HTTP.get_response(URI.parse(url))
  rescue
    return url
  end
  case response
  when Net::HTTPRedirection
    expand_url(response['location'])
  else
    url
  end
end

puts expand_url("http://bit.ly/ICFCzV")
11
9
0

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
11
9