Class: Guillotine::Adapter

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

Overview

Adapters handle the storage and retrieval of URLs in the system. You can use whatever you want, as long as it implements the #add and #find methods. See MemoryAdapter for a simple solution.

Instance Method Summary collapse

Instance Method Details

#parse_url(url) ⇒ Object

Parses and sanitizes a URL.

url - A String URL.

Returns an Addressable::URI.



45
46
47
48
49
# File 'lib/guillotine.rb', line 45

def parse_url(url)
  url.gsub! /\s/, ''
  url.gsub! /(\#|\?).*/, ''
  Addressable::URI.parse url
end

#shorten(url) ⇒ Object

Public: Shortens a given URL to a short code.

1) MD5 hash the URL to the hexdigest 2) Convert it to a Bignum 3) Pack it into a bitstring as a big-endian int 4) base64-encode the bitstring, remove the trailing junk

url - String URL to shorten.

Returns a unique String code for the URL.



36
37
38
# File 'lib/guillotine.rb', line 36

def shorten(url)
  Base64.urlsafe_encode64([Digest::MD5.hexdigest(url).to_i(16)].pack("N")).sub(/==\n?$/, '')
end