Last active
October 21, 2018 11:30
-
-
Save harrisonmalone/55671deecfc57550d2c698bd474ef3c2 to your computer and use it in GitHub Desktop.
bit.ly rails copy
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
<h1>Link shortener</h1> | |
<%= form_for(Link.new, url: link_path) do |f| %> | |
<%= f.text_field :original_url %> | |
<%= f.submit "Create short link" %> | |
<% end %> |
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 LinksController < ApplicationController | |
def index | |
end | |
def show | |
@link = Link.find(params[:id]) | |
end | |
def go_to_link | |
link = Link.find_by_hash_value(params[:hash]) | |
if !link.original_url.include?("http") | |
redirect_to "https://#{link.original_url}" | |
else | |
redirect_to link.original_url | |
end | |
end | |
def create | |
@link = Link.new(link_params) | |
respond_to do |format| | |
if @link.save | |
format.html { redirect_to(link_show_path(@link)) } | |
format.json { render :json => @link, :status => :created, :location => @link } | |
else | |
format.html { render :action => "index" } | |
format.json { render :json => @link.errors, :status => :unprocessable_entity } | |
end | |
end | |
@link.hash_value = @link.id.to_s(36) | |
@link.save | |
end | |
private | |
def link_params | |
params.require(:link).permit(:original_url) | |
end | |
end |
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
Rails.application.routes.draw do | |
root to: 'links#index' | |
get 'links/:id', to: 'links#show', as: 'link_show' | |
post 'link', to: 'links#create' | |
get '/:hash', to: 'links#go_to_link', as: 'go_to_link' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment