Micro web server
A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve web pages to users. In this step we are going to use a microframework to build a simple web server to serve our wishlist platform. A microframework is a term used to refer to minimalistic web application frameworks. It is contrasted with full-stack frameworks.
Sinatra
Sinatra is a DSL (Domain Specific Language) for quickly creating web applications in Ruby with minimal effort.
Create a server.rb
file with the following content:
require 'sinatra'
get '/' do
'Hello world!'
end
In order to use the sinatra library, you will first need to install it:
gem install sinatra
A gem is a module/library that you can install and use in every project that you need.
Now you can run your server by doing:
ruby server.rb
If you navigate to localhost:4567
on your browser you will see the response from the server to your request.
Let’s add an HTML view. Put the following code into an index.erb
file inside the views
directory (you will need to create it):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
</head>
<body>
<h1><%= @message %></h1>
</body>
</html>
change your endpoint code to:
get '/' do
@title = 'Hello World!'
erb :index
end
All instance variables will be available in the view for you to use. We are using the erb
extension on the view file. ERB (Embedded RuBy) is a feature of Ruby that enables you to use Ruby to generate text, in our case HTML text.
Exercise 1
Let's use Sinatra to serve the wishlist items platform we created in the Javascript section. Convert all your .html
files to .erb
and create endpoints to return these views and handle all existing functionality.
Use global variables to store the created favourite items and the max budget. Use a class to model the wishlist item.
NOTE:
If you want to show assets (i.e. images) on your views, you will need to create a public
folder and store your assets there.
Exercise 2
Now, use a database to store the created favourite items. Use the pg
gem as the interface to interact with a PostgreSQL database.
Exercise 3
Let's add a search input (and endpoint) that filters the wishlist items based on their name.