Sha256: a172e01fa1c6938c82cbbd220fa1e74e4e8915a99686cfc10b0476c6cd8710a7

Contents?: true

Size: 1.07 KB

Versions: 5

Compression:

Stored size: 1.07 KB

Contents

require 'sawyer'

module Octospy
  module Url
    class << self
      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

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

      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

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

      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
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
octospy-0.2.0 lib/octospy/url.rb
octospy-0.1.1 lib/octospy/url.rb
octospy-0.1.0 lib/octospy/url.rb
octospy-0.0.8 lib/octospy/url.rb
octospy-0.0.7 lib/octospy/url.rb