Module: Octospy::Url

Defined in:
lib/octospy/url.rb

Class Method Summary collapse

Class Method Details

.github_shortener_endpointObject



17
18
19
# File 'lib/octospy/url.rb', line 17

def github_shortener_endpoint
  'http://git.io/'
end

.google_shortener_endpointObject



30
31
32
# File 'lib/octospy/url.rb', line 30

def google_shortener_endpoint
  'https://www.googleapis.com/urlshortener/v1/'
end

.shorten(url) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/octospy/url.rb', line 6

def shorten(url)
  case
  when url =~ /https?:\/\/(\w+\.)?github\.com/
    self.shorten_by_github url
  when url =~ /https?:\/\/.+/
    self.shorten_by_google url
  else
    url
  end
end

.shorten_by_github(url) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/octospy/url.rb', line 21

def shorten_by_github(url)
  agent = Sawyer::Agent.new(self.github_shortener_endpoint)
  response = agent.call(:post, '', "url=#{url}")
  response.headers[:location]
rescue => e
  puts e.message
  url
end

.shorten_by_google(url) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/octospy/url.rb', line 34

def shorten_by_google(url)
  agent = Sawyer::Agent.new(self.google_shortener_endpoint) do |http|
    http.headers['Content-Type'] = 'application/json'
  end
  response = agent.call(:post, 'url', longUrl: url)
  response.data.attrs[:id]
rescue => e
  puts e.message
  url
end