Class: MongoidShortener::ShortenedUrl

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Timestamps
Defined in:
app/models/mongoid_shortener/shortened_url.rb

Constant Summary collapse

URL_PROTOCOL_HTTP =
"http://"
REGEX_HTTP_URL =
/^\s*(http[s]?:\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\s*$/i
Regexp.new('\Ahttp:\/\/|\Ahttps:\/\/', Regexp::IGNORECASE)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.generate(orig_url) ⇒ Object

return shortened url on success, nil on failure



66
67
68
69
70
71
72
73
74
75
76
# File 'app/models/mongoid_shortener/shortened_url.rb', line 66

def self.generate(orig_url)
  sl = nil

  begin
    sl = ShortenedUrl::generate!(orig_url)
  rescue
    sl = nil
  end

  return sl
end

.generate!(orig_url) ⇒ Object

generate a shortened link from a url link to a user if one specified throw an exception if anything goes wrong



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/models/mongoid_shortener/shortened_url.rb', line 47

def self.generate!(orig_url)
  if !orig_url.blank? and orig_url !~ REGEX_LINK_HAS_PROTOCOL
    orig_url.insert(0, URL_PROTOCOL_HTTP)
  end

  # don't want to generate the link if it has already been generated
  # so check the datastore
  sl = ShortenedUrl.where(:url => orig_url).first

  return MongoidShortener.prefix_url + sl.unique_key if sl

  # create the shortened link, storing it
  sl = ShortenedUrl.create!(:url => orig_url)

  # return the url
  return MongoidShortener.prefix_url + sl.unique_key
end

Instance Method Details

#clean_destination_urlObject

ensure the url starts with it protocol



31
32
33
34
35
# File 'app/models/mongoid_shortener/shortened_url.rb', line 31

def clean_destination_url
  if !self.url.blank? and self.url !~ REGEX_LINK_HAS_PROTOCOL
    self.url.insert(0, URL_PROTOCOL_HTTP)
  end
end

#init_unique_keyObject



37
38
39
40
41
42
# File 'app/models/mongoid_shortener/shortened_url.rb', line 37

def init_unique_key
  # generate a unique key for the link
  begin
    self.unique_key = YAB62.encode62(ShortenedUrl::count)
  end while ShortenedUrl::where(:unique_key => self.unique_key).first
end