Class: UrlShortening::Url

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/url_shortening/url.rb

Constant Summary collapse

CHARSET =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASE =
62

Class Method Summary collapse

Class Method Details

.get_long_url(short_url) ⇒ Object



24
25
26
27
28
29
30
31
# File 'app/models/url_shortening/url.rb', line 24

def self.get_long_url(short_url)
  hash = get_path(short_url)
  if hash
    id = decode(hash)
    url = find_by_id(id)
    url.long if url
  end
end

.get_short_url(long_url) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'app/models/url_shortening/url.rb', line 10

def self.get_short_url(long_url)
  uri = URI.parse(long_url)
  if uri.host && uri.path.present?
    url = find_or_create_by(long: long_url)
    unless url.short
      hash = encode(url.id)
      url.update(short: hash)
    end
    "#{uri.scheme}://#{uri.host}/#{url.short}"
  else
    raise "This Url cannot be shortened!, might be not correct url or too short to be shortened."
  end
end