文章中の bit.ly などの短縮URL を元に戻す Rubyスクリプト
タイトルどおりのことをやってくれるスクリプトです。欲しくなったのでつくりました。自分用メモです。
スクリプト lengthen.rb の内容は次のようにします。
# coding: utf-8 # やってないこと: # - 複数のURL。元に戻すURL は 1文章につき 1つまで。それ以降の URL は無視する # - https の対応。含んでいるとエラー... # - URL が含まれていない場合の対応。エラー... require 'net/http' require 'uri' # 短縮URL を含む文章 sentences = [ 'http://bit.ly/TieOFQ 最初', '途中 http://qr.net/j7YA 途中', '最後 http://p.tl/DqEH' ] puts '------------- Before -------------' sentences.each {|sentence| puts sentence } replaced_sentences = sentences.map {|sentence| # see: http://www.din.or.jp/~ohzaki/perl.htm#httpURL url_exp = /s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:@&=+$,%#]+/ match_data = sentence.match(url_exp) url = URI.parse(match_data.to_s) response = Net::HTTP.start(url.host, url.port) {|http| http.get(url.path) } sentence.gsub(match_data.to_s, response.to_hash['location'][0]) } puts '------------- After -------------' replaced_sentences.each {|sentence| puts sentence }
実行結果。
$ ruby lengthen.rb ------------- Before ------------- http://bit.ly/TieOFQ 最初 途中 http://qr.net/j7YA 途中 最後 http://p.tl/DqEH ------------- After ------------- http://gogengo.me/roots/304 最初 途中 http://gogengo.me/ 途中 最後 http://gogengo.me/words/275
うん。べんり^^