Created
April 22, 2014 03:32
-
-
Save kenyonj/11164540 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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