/models/url.rb

http://github.com/dennmart/mongoshort · Ruby · 35 lines · 28 code · 4 blank · 3 comment · 3 complexity · c7f020548f81e7926973a6982707550c MD5 · raw file

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