edit-chi-parkour

The Rails Request, Part 1: the basics

As I began learning Rails, I really struggled to gain a solid understanding of the way that Rails handles the request-response cycle. I simultaneously knew too little about programming in general and about HTTP specifically, to really understand what was going on behind the scenes. The fact that many of my problems were google-able also served as a sort of crutch. But in order to truly understand how your web app works, you need to be aware of the path your data is taking in the request-response cycle.

I learned Ruby pretty much at the same time that I learned Rails. In truth, I tried to get a head start on Ruby, probably spending two or three weeks learning it before I touched Rails, not enough to adequately familiarize myself with core programming concepts. More experience would have helped me realize that serving web pages is really no different than any other type of programming.

At their core, web app are still calling functions, passing parameters, and returning values.

Unfortunately, this didn’t sink in for quite a while.

With the web, the function is called from the browser. This is the best and worst part of internet communication. On the one hand, it’s an incredible advancement in technology that I can essentially call a function and pass some parameters to any computer in the world that will let me. But what is difficult about the web, is there is a fair amount of translation from language to language. We need to be able to keep track of those transformations.

Let’s start with an example request response cycle. Somebody half-way around the world types [insert_my_app].com’ into their address bar and hits ‘ENTER’. The browser encodes the URL into an HTTP header. This is the first translation. Through the dark magic of DNS, this HTTP request somehow gets to our Rails server. There the request is matched to the root route (because the path is technially ‘/’) and it gets forwarded on to a function(called an ‘action’ in Rails), which ultimately renders a view. This view, using HAML or ERB (or some other templating language), translates Ruby into HTML. link_tos and form_fors are transformed into <a> tags and <form> tags, which when clicked or submitted, will be transformed again into HTTP requests. The requests will in turn be parsed and routed by Rails, so that we can interact with that data in Ruby again.

Because the data of the request transforms three times every cycle, it’s important to have a solid understand of HTML and HTTP in addition to understanding Ruby and Rails. This is particularly important where as developers, we are driving these transformations every step of the way. We are giving the users the links to click on and the forms to fill out.

In Part 2 of this series, we’ll be discussing http verbs and URL paths.