Created
November 16, 2021 13:46
-
-
Save walterdavis/219fb2bb4e57501ac53303608c4d693b to your computer and use it in GitHub Desktop.
This file contains 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
# rails new shrtn | |
# cd shrtn | |
# rails g model Site url:uniq slug:index | |
# rake db:migrate | |
# site.rb | |
class Site < ApplicationRecord | |
after_create :generate_slug | |
delegate :url_helpers, to: 'Rails.application.routes' | |
def to_param | |
slug | |
end | |
def short_url | |
url_helpers.site_url(self) | |
end | |
private | |
def generate_slug | |
length = 3 | |
loop do | |
slug = to_sha(length) | |
return self.slug = slug unless Site.find_by(slug: slug) | |
length = length + 1 | |
end | |
end | |
def to_sha(size = nil) | |
sha = Digest::SHA256.hexdigest("#{url}:#{created_at}") | |
return sha.slice(0,size) if size | |
sha | |
end | |
end | |
# sites_controller.rb | |
class SitesController < ApplicationController | |
def get | |
set_site | |
redirect_to @site.url | |
end | |
def create | |
@site = Site.where(url: params[:url]).first_or_create | |
render text: @site.short_url | |
end | |
private | |
def set_site | |
@site = Site.find_by! slug: params[:slug] | |
end | |
end | |
# routes.rb | |
Rails.application.routes.draw do | |
post 'sites/:url', to: 'sites#create' | |
get '/:slug', to: 'sites#get', as: :site | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment