Week 3 at Makers
This week we looked at web applications.
Hypertext transfer protocol
On a very high-level, a web application is a series of requests and responses between client and server. The user selects an action on their browser (other user agents are available), the browser requests this action from the server, and the server responds with the requested content. This is the basis of hypertext transfer protocol (HTTP).
The request comprises the request line, headers and content. The request line comprises the the method (GET, POST etc.), the request URI (universal request identifier of the resource upon which to apply the request) and the HTTP version. Headers contains various metadata related to the request. The content of the request varies, but may include for example a string of fields and values like “name=Bob&age=30” from a submitted form that asked for name and age.
The response is similar, but contains a status line instead of the request line. The status line contains the HTTP version, the status code and the reason phrase. The status code is a 3-digit number that corresponds to the server’s attempt at satisfying the request, and the reason phrase gives a short description of the status code. For example: “200 OK” or “404 Not Found”. The response content is generally HTML to be rendered by the browser, but can also be JSON, XML or other data.
Model-view-controller
The most common pattern for building web applications is model-view-controller (MVC).
The model is the core data and logic of the application. This corresponds to the Ruby classes and functions that do most of the heavy lifting behind the scenes of a Ruby web application.
The view is the representation of the data from the model for the end user. Embedded Ruby achieves this by allowing HTML to be dynamically generated by Ruby. Ruby expressions and logic can be used to render data and to render HTML elements conditionally.
The controller is the medium between the user and the model. It takes user input and passes user instructions to the model. Sinatra can take this role. Sinatra is a domain-specific language for building web applications, i.e. a special language just for controlling routing, requests and responses for websites.
Testing web applications
Capybara is a Ruby gem which can be used with RSpec to conduct feature tests for web applications. It interacts with the application in a similar way to a real user. You can tell it to visit a certain path, fill in forms, click buttons and links, as well as check that desired content is present on the page.