Skip to content

Instantly share code, notes, and snippets.

@kenyonj
Created April 22, 2014 03:32
Show Gist options
  • Save kenyonj/11164540 to your computer and use it in GitHub Desktop.
Save kenyonj/11164540 to your computer and use it in GitHub Desktop.
class Url < ActiveRecord::Base
before_create :generate_unique_token, :escape_original_url
validates :original_url, presence: true
validate :check_if_url_is_valid
def to_param
token
end
private
def check_if_url_is_valid
unless original_url.strip.downcase.start_with?('http')
errors.add(:url, 'must start with http or https.')
end
end
def escape_original_url
self.original_url = URI.escape(original_url.strip)
end
def generate_unique_token
self.token = SecureRandom.hex(2)
while Url.exists?(token: token)
self.token = SecureRandom.hex(2)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment