DEV Community

Cover image for Sinatra Ruby Web App
sarisgar28
sarisgar28

Posted on • Edited on

Sinatra Ruby Web App

Hi Guys!
This has been crazy times, for the world and as a student is been the hardest months in terms of learning to code...
I am a student in Flatiron School and for our second module we need to create a Sinatra Web App using MVC which stands for MODELS, VIEWS AND CONTROLLERS!
I've noticed that my previous post was a little meh on showing my experience doing this application so I will share a little more on this post.
I am going to share some of my files from my app hoping it will be helpful for you. In my application I am using,Sinatra Active Record, MVC, CRUD as well as uniqueness of validation for user login attribute.
First I would like to share my Gemfile...

gem "sinatra", "~> 2.0"

gem "require_all", "~> 3.0"

gem "pry", "~> 0.13.1"

gem "shotgun", "~> 0.9.2"

gem "activerecord", "~> 6.0"

gem "sinatra-activerecord", "~> 2.0"

gem "sqlite3", "~> 1.4"

gem "rake", "~> 13.0"

gem "bundler", "~> 2.1"

gem "bcrypt", "~> 3.1"

You will need to set up your controllers as well as your views to make sure your app is working, make sure you use Session Secret and enable your Sessions just like this code below.

class ApplicationController < Sinatra::Base

set :views, ->{File.join(root,'../views')}
enable :sessions
set :session_secret, ENV["SESSION_SECRET"]
Enter fullscreen mode Exit fullscreen mode

end
Once you have this you can get started with your SINATRA CRUD, which stands for Create, Read, Update and Destroy.

class SessionsController < ApplicationController

get '/login' do 
    erb :"sessions/login"
end 

get '/signup' do 
    erb :'sessions/signup'
end 

post '/signup' do
    @user = User.new(username: params[:username], password: params[:password])
    if @user.save 
        session[:user_id] = @user.id 
        redirect'/cocktails'
    else
     erb :"sessions/signup"
    end
end 

post '/login' do 
     user = User.find_by(username: params[:username])
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect'/cocktails'
    else  
        @error = "Invalid Username or Password"
        erb :"sessions/login"

    end 
end 

delete '/logout' do 
    session.clear
    redirect '/home'
    erb :'/cocktails'
end 
Enter fullscreen mode Exit fullscreen mode

end
I've been RESTful in my code because is a requirement on my project, I think is a good practice to follow but is your choice to whether you use it or not.
I am happy to share my GitHub page so you guys can see my complete project, I hope this post is somewhat helpful to you.

https://github.com/sarisgar28/sinatra_project

Happy Coding!

Top comments (0)