Module: UrlShorty
- Defined in:
- lib/url_shorty.rb,
lib/url_shorty/utils.rb,
lib/url_shorty/version.rb,
lib/url_shorty/analytics.rb
Overview
Constant Summary collapse
- BASE_URL =
"https://www.googleapis.com/urlshortener/v1/url?key="
- SHORT_URL =
"&shortUrl="
- PROJECTION =
"&projection=FULL"
- VERSION =
"0.0.13"
Class Method Summary collapse
-
.api_key(api_key) ⇒ Object
UrlShorty.api_key(“<API KEY>”).
-
.expand_url(shorten_url) ⇒ String
This method will expand the shortened URL into a long URL Example:.
-
.get_analytics(shorten_url) ⇒ Object
>“Macintosh”.
-
.shorten_url(long_url) ⇒ String
This method will shorten the provided long URL into a short URL using the Google URL shortener service.
Class Method Details
.api_key(api_key) ⇒ Object
UrlShorty.api_key(“<API KEY>”)
20 21 22 |
# File 'lib/url_shorty.rb', line 20 def self.api_key (api_key) @api_key = api_key end |
.expand_url(shorten_url) ⇒ String
This method will expand the shortened URL into a long URL Example:
UrlShorty.expand_url("https://goo.gl/XojnVs")
=> "https://github.com/Balaji-Ramasubramanian/UrlShorty"
59 60 61 62 63 64 65 66 67 |
# File 'lib/url_shorty.rb', line 59 def self.(shorten_url) url = BASE_URL + @api_key + SHORT_URL + shorten_url response = "" response = HTTParty.get(url) parsed = JSON.parse(response.body) long_url = parsed['longUrl'] puts long_url return long_url end |
.get_analytics(shorten_url) ⇒ Object
>“Macintosh”
53 54 55 56 57 58 59 |
# File 'lib/url_shorty/analytics.rb', line 53 def self.get_analytics (shorten_url) url = BASE_URL + @api_key + SHORT_URL + shorten_url + PROJECTION response = "" response = HTTParty.get(url) parsed_json_obj = JSON.parse(response.body, object_class: OpenStruct) return parsed_json_obj end |
.shorten_url(long_url) ⇒ String
This method will shorten the provided long URL into a short URL using the Google URL shortener service. Example:
UrlShorty.shorten_url(""https://github.com/Balaji-Ramasubramanian/UrlShorty")
=> "https://goo.gl/XojnVs"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/url_shorty.rb', line 32 def self.shorten_url(long_url) uri = URI.parse( BASE_URL + @api_key ) header = {'Content-Type': 'application/json'} parameter = {"longUrl": "#{long_url}"} http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.request_uri, header) request.body = parameter.to_json response = http.request(request) data = JSON.parse(response.body) if data["id"] != nil then return data["id"] else puts data return data["error"]["errors"][0]["reason"] end end |