Every morning before I start my day I make a coffee, fire up my phone and visit chicagotribune.com. While my coffee brews and my home fills with a delicious vanilla-swirl aroma I sleepily get the latest in local news. So how does this work? How am I able to read about Chance the Snapper in such an easy and convenient way?
The Basics of visiting a website
Working on my Sinatra Project was a great introduction to getting a base understanding of how the internet works.
step 1 User(client) types URL into browser.
step 2 The server then receives the request, processes it, and sends a response.
step 3 Your browser receives that response and shows to user.
TL;DR: Browsers send requests, and servers send responses.
Hypertext Transfer Protocol (HTTP)
Is the protocol used to transfer data over the web.
Parameter
A parameter is a hash and a powerful tool that is used to capture and use data that the user inputs.
Request Method (a.k.a HTTP verb)
Indicate the desired action to be performed on the identified resource.
Route
Routing is how your app responds to requests, by the path of the request and by the HTTP verb used.
[http-verb] [path] do
[code block to execute when this route is requested]
end
Putting it all together
post '/users' do
@user = User.new
@user.username = params[:username]
@user.email = params[:email]
@user.password = params[:password]
if @user.save
session["user_id"] = @user.id
redirect '/'
else
erb :'users/new.html'
end
end
The above is a snippet of code from my Sinatra project. It is part of the users controller (good ole MVC). After the user has successfully been directed to the programs registration form, the form has been filled out and they click 'save' the code mentioned will come into play. Within the POST method I wrote code that would allow a user to save a personalized profile. This was possible by creating parameters that would capture the users input and save that data as a hash. Once the user has saved their registration form their information is saved in the programs database. Thanks to the handy parameters in the saved user input is now available.
If say we wanted to check out a specific users logs, the following code would allow that...
get '/logs/:id' do
@log = current_user.logs.find_by(id: params[:id]) # ensures that you only have access to your log and nobody elses
# find_by over find
erb :"logs/show.html"
end
The above GET method allow us to route through not just the logs but also by user. How is that possible? Well with routing parameters - parts of the URL that will change based on the object we want to display.
In conclusion, I had a ton of fun working on this project and while there is a bit of a learning curve, which I'm still powering through, I'm enjoying every second of learning about coding and learning how to learn.
Top comments (0)