Class: GoShortener
- Inherits:
-
Object
- Object
- GoShortener
- Defined in:
- lib/goshortener.rb
Instance Method Summary collapse
-
#initialize(api_key = "") ⇒ GoShortener
constructor
initialize with/without api key.
-
#lengthen(short_url) ⇒ Object
Given a short URL, Returns the true long url using goo.gl service.
-
#shorten(long_url) ⇒ Object
Given a long URL, Returns the true short url using goo.gl service.
Constructor Details
#initialize(api_key = "") ⇒ GoShortener
initialize with/without api key
10 11 12 13 |
# File 'lib/goshortener.rb', line 10 def initialize(api_key="") @api_key = api_key unless api_key == "" @base_url = "https://www.googleapis.com/urlshortener/v1/url" end |
Instance Method Details
#lengthen(short_url) ⇒ Object
Given a short URL, Returns the true long url using goo.gl service
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/goshortener.rb', line 33 def lengthen(short_url) if short_url.is_a?(String) request_params = {:shortUrl => short_url} request_params.merge!(:key => @api_key) if @api_key begin response = RestClient.get @base_url, :params => request_params rescue raise InvalidUrlError, "Please provide a valid URL" end else raise "Please provide a valid http://goo.gl url String" end response = JSON.parse response response["longUrl"] end |
#shorten(long_url) ⇒ Object
Given a long URL, Returns the true short url using goo.gl service
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/goshortener.rb', line 16 def shorten(long_url) if long_url.is_a?(String) request_json = {'longUrl' => long_url}.to_json request_url = @api_key ? (@base_url + "?key=#{@api_key}") : @base_url begin response = RestClient.post request_url, request_json, :accept => :json, :content_type => :json rescue raise InvalidUrlError, "Please provide a valid URL" end else raise "Please provide a url String" end response = JSON.parse response response["id"] end |