Google URL Shortener APIを利用してURLを短縮・展開する

コード

require 'net/https'
require 'json'

module Google
  module UrlShortener
    def self.shorten_url(url, api_key=nil)
      send_request {
        req = Net::HTTP::Post.new("/urlshortener/v1/url#{api_key ? '?key=' + api_key : ''}", 'Content-Type' => 'application/json')
        req.body = "{'longUrl':'#{url}'}"
        req
      }["id"]
    end

    def self.expand_url(short_url, api_key=nil)
      send_request {
        Net::HTTP::Get.new("/urlshortener/v1/url?shortUrl=#{short_url}#{api_key ? '&key=' + api_key : ''}")
      }["longUrl"]
    end

    private

    def self.send_request
      https = Net::HTTP.new('www.googleapis.com',443)
      https.use_ssl = true
      https.verify_mode = OpenSSL::SSL::VERIFY_PEER
      req = yield
      res = https.start { https.request(req) }
      JSON.parse(res.body)
    end
  end
end

使い方

APIキーを使わない場合
short_url = Google::UrlShortener.shorten_url("http://www.yahoo.co.jp/") # => "http://goo.gl/wNOy"
long_url = Google::UrlShortener.expand_url(short_url) # => "http://www.yahoo.co.jp"
APIキーを使う場合
short_url = Google::UrlShortener.shorten_url("http://www.yahoo.co.jp", "YOUR_API_KEY") # => "http://goo.gl/wNOy"
long_url = Google::UrlShortener.expand_url(short_url, "YOUR_API_KEY") # => "http://www.yahoo.co.jp/"