Class: GoogleShortener

Inherits:
Object
  • Object
show all
Defined in:
lib/google_shortener.rb

Constant Summary collapse

PROJECTIONS =
['FULL', 'ANALYTICS_CLICKS', 'ANALYTICS_TOP_STRINGS']

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGoogleShortener



9
10
11
# File 'lib/google_shortener.rb', line 9

def initialize
  @api_key = 'AIzaSyDOY31us5qGR_MdMQKaTfGlhpOi8w3Ur7U'
end

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



5
6
7
# File 'lib/google_shortener.rb', line 5

def api_key
  @api_key
end

Instance Method Details

#analytics(short_url, projection = 'FULL') ⇒ Object

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/google_shortener.rb', line 46

def analytics(short_url, projection='FULL')
  raise ArgumentError, "Short URL should be a String" unless short_url.is_a?(String)

  if short_url.empty?
    raise ArgumentError, 'Short URL is required'
  end

  raise ArgumentError, "Projection should be a String" unless projection.is_a?(String)
  raise ArgumentError, "Projection can only be #{PROJECTIONS.join(',')}" unless PROJECTIONS.include?(projection)

  res = get_from_google_url_shortener_api(short_url, {'projection' => projection})
  res_body = JSON.load(res.body)
end

#expand(short_url) ⇒ Object

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/google_shortener.rb', line 30

def expand(short_url)
  raise ArgumentError, "Short URL should be a String" unless short_url.is_a?(String)

  if short_url.empty?
    raise ArgumentError, 'Short URL is required'
  end
  res = get_from_google_url_shortener_api(short_url)
  res_body = JSON.load(res.body)

  if res.is_a?(Net::HTTPSuccess)
    res_body['longUrl']
  else
    res_body
  end
end

#shorten(long_url) ⇒ Object

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/google_shortener.rb', line 13

def shorten(long_url)
  raise ArgumentError, "Long URL should be a String" unless long_url.is_a?(String)

  if long_url.empty?
    raise ArgumentError, 'Long URL is required'
  end

  res = post_to_google_url_shortener_api(long_url)
  res_body = JSON.load(res.body)

  if res.is_a? Net::HTTPSuccess
    res_body['id']
  else
    res_body
  end
end

#valid_api_key?Boolean



60
61
62
63
64
65
66
67
68
# File 'lib/google_shortener.rb', line 60

def valid_api_key?
  res = post_to_google_url_shortener_api('http://www.google.com')

  if res.is_a?(Net::HTTPSuccess)
    true
  else
    false
  end
end