goshortener 1.2.1 → 1.2.2
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/goshortener.rb +9 -16
- metadata +1 -1
data/lib/goshortener.rb
CHANGED
@@ -2,14 +2,13 @@ require "rubygems"
|
|
2
2
|
require "rest_client"
|
3
3
|
require "json"
|
4
4
|
|
5
|
+
class InvalidUrlError < Exception; end
|
5
6
|
|
6
7
|
class GoShortener
|
7
8
|
|
8
9
|
#initialize with/without api key
|
9
10
|
def initialize(api_key="")
|
10
|
-
unless api_key == ""
|
11
|
-
@api_key = api_key
|
12
|
-
end
|
11
|
+
@api_key = api_key unless api_key == ""
|
13
12
|
@base_url = "https://www.googleapis.com/urlshortener/v1/url"
|
14
13
|
end
|
15
14
|
|
@@ -18,19 +17,16 @@ class GoShortener
|
|
18
17
|
if long_url.is_a?(String)
|
19
18
|
request_json = {'longUrl' => long_url}.to_json
|
20
19
|
request_url = @api_key ? (@base_url + "?key=#{@api_key}") : @base_url
|
21
|
-
|
22
20
|
begin
|
23
21
|
response = RestClient.post request_url, request_json, :accept => :json, :content_type => :json
|
24
|
-
rescue
|
25
|
-
raise "Please provide a valid
|
22
|
+
rescue
|
23
|
+
raise InvalidUrlError, "Please provide a valid URL"
|
26
24
|
end
|
27
|
-
|
28
25
|
else
|
29
|
-
raise "Please provide a
|
26
|
+
raise "Please provide a url String"
|
30
27
|
end
|
31
28
|
response = JSON.parse response
|
32
|
-
|
33
|
-
return short_url
|
29
|
+
response["id"]
|
34
30
|
end
|
35
31
|
|
36
32
|
#Given a short URL, Returns the true long url using http://goo.gl service
|
@@ -38,19 +34,16 @@ class GoShortener
|
|
38
34
|
if short_url.is_a?(String)
|
39
35
|
request_params = {:shortUrl => short_url}
|
40
36
|
request_params.merge!(:key => @api_key) if @api_key
|
41
|
-
|
42
37
|
begin
|
43
38
|
response = RestClient.get @base_url, :params => request_params
|
44
39
|
rescue
|
45
|
-
raise "Please provide a valid
|
40
|
+
raise InvalidUrlError, "Please provide a valid URL"
|
46
41
|
end
|
47
|
-
|
48
42
|
else
|
49
|
-
raise "Please provide a valid goo.gl
|
43
|
+
raise "Please provide a valid http://goo.gl url String"
|
50
44
|
end
|
51
45
|
response = JSON.parse response
|
52
|
-
|
53
|
-
return long_url
|
46
|
+
response["longUrl"]
|
54
47
|
end
|
55
48
|
|
56
49
|
end
|