PageRenderTime 24ms CodeModel.GetById 19ms app.highlight 4ms RepoModel.GetById 0ms app.codeStats 0ms

/models/url.rb

http://github.com/dennmart/mongoshort
Ruby | 35 lines | 28 code | 4 blank | 3 comment | 3 complexity | c7f020548f81e7926973a6982707550c MD5 | raw file
 1class URL
 2  include MongoMapper::Document
 3
 4  key :url_key, String, :required => true
 5  key :full_url, String, :required => true
 6  key :last_accessed, Time
 7  key :times_viewed, Integer, :default => 0
 8  
 9  # Tip for URL validation taken from http://mbleigh.com/2009/02/18/quick-tip-rails-url-validation.html
10  validates_format_of :full_url, :with => URI::regexp(%w(http https))
11
12  def self.find_or_create(new_url)
13    url_key = Digest::MD5.hexdigest(new_url)[0..4]
14    begin
15      # Check if the key exists, so we don't have to create the URL again.
16      url = self.find_by_url_key(url_key)
17      if url.nil?
18        url = URL.new(:url_key => url_key, :full_url => new_url)
19        url.save!
20      end
21      return { :short_url => url.short_url, :full_url => url.full_url }
22    rescue MongoMapper::DocumentNotValid
23      return { :error => "'url' parameter is invalid" }.to_json
24    end
25  end
26
27  def short_url
28    # Note that if running locally, 'Sinatra::Application.host' will return '0.0.0.0'.
29    if Sinatra::Application.port == 80
30      "http://#{Sinatra::Application.bind}/#{self.url_key}"
31    else
32      "http://#{Sinatra::Application.bind}:#{Sinatra::Application.port}/#{self.url_key}"
33    end
34  end
35end