class Googleurlshortener::Default

Public Instance Methods

expand(short_url) click to toggle source
# File lib/googleurlshortener.rb, line 25
def expand(short_url)
  json = get_json_response("https://www.googleapis.com/urlshortener/v1/url?shortUrl=#{short_url}")
  return json["longUrl"]
end
shorten(long_url) click to toggle source
# File lib/googleurlshortener.rb, line 10
def shorten(long_url)
  uri = URI("https://www.googleapis.com/urlshortener/v1/url")
  body = ""
  Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    request = Net::HTTP::Post.new uri.request_uri
    if defined? @auth_token && @auth_token != "" && @auth_token != nil
      request['Authorization'] = @auth_token
    end
    request["Content-Type"] = "application/json"
    response = http.request(request, "{\"longUrl\": \"#{long_url}\"}")
    body = response.body
  end
  return JSON.parse(body)["id"]
end

Private Instance Methods

get_json_response(url) click to toggle source
# File lib/googleurlshortener.rb, line 32
def get_json_response(url)
  uri = URI(url)
  request = Net::HTTP::Get.new(uri.request_uri)
  if self.class.name == "Googleurlshortener::Authenticated"
    request['Authorization'] = @auth_token
  end
  response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') {|http|
    http.request(request)
  }
  return JSON.parse(response.body)
end