Useful Ruby Methods For Sinatra (possibly, most likely, also for Rails)

configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :I'm not showing you this
end
helpers do def logged_in?(session)
!!session[:user_id]
end
def current_user
User.find_by(id: session[:user_id])
end
end
post '/login' do
user = User.find_by(name: params[:name])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect "/users/#{user.id}"
else
redirect '/login'
end
end
patch '/items/:id' do 
@item = Item.find(params[:id])
if current_user.id == @item.id
@item.assign_attributes(params[:item])
if @item.save
redirect '/items'
else
erb :'items/edit'
end
else
redirect '/items'
end
end
<div class="item form">
<h1>Edit Your Item</h1>
<div>
<form action="/items/<%=@item.id%>" method="post">
<input type="hidden" name="_method" value="patch">
<div class="form-group"><label>Name</label>
<input type="text" class="form-control" name="name"
required value="<%=@item.name%>"><br>
<label>Description</label>
<input type="text" class="form-control" name="description"
required value="<%=@item.description%>"><br>
<label>Item Image URL</label>
<input type="text" class="form-control" name="item_image_url" required value="<%=@item.item_image_url%>"><br>
</div><button type="submit" class="btn btn-primary">Submit</button>
</form>
<p><a href="/items/<%=@item.id%>">Back to your account</a></p><p><form action="/items/<%=@item.id%>" method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="Delete Item">
</form></p>
</div>
delete '/items/:id' do
@item = Item.find(params[:id])
if current_user.id == @item.user_id
@item.destroy
redirect '/items'
else
redirect '/items'
end
end

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Support for AWS IAM Instance Profiles

CS373 Spring 2022: William Johnston

Synthetix: Open DeFi Hackathon Winners

Python Programming: Guesssing Game

Amazon EC2 Deployment: Complete CI/CD Pipeline using GitHub Actions and AWS CodeDeploy

WWDC 2018 — Analysis and Review

Top 4 Magento marketplace extensions to boost your eCommerce sales effectively

Magento Marketplace extension by Webnexs

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arslan Ali

Arslan Ali

More from Medium

ruby-build: definition not found: x.x.x

BCrypt and Salt in Ruby: What’s happening?

Namespacing: Modules’ other main job

Rails still worth learning in 2022?