Rack TTT

One of my tasks has been to add a web version of my already existing ruby tic tac toe using rack. The purpose of this task is to learn how important it is keeping code abstract. When the code is abstract it is more flexible and easier to add new features. My initial tic tac toe was all in one project, and it could only be played on console.

The first step I made, was to separate the console code into another project and turn the existing one into the core gem. I turned it into a gem as it makes the code easily portable. Once I created the gem I added it to the Gemfile of the console tic tac toe project and then ran all of the tests making sure everything was passing.

I was then in a position where I could create another project specifically for the rack version. To start this off I was spiking to get an understanding of how rack worked. I managed to create a config.ru and a TTTRack object. When running rackup on the config it would run web brick (http server) and create an instance of TTTRack. Within the TTTRack there is a call method which gets invoked when ever a user sends a request to the server, this method will always be called with the request data and return a http response. This response is in the format of an array which holds the status code, content type and content body.

To draw my board I created an instance of Board (which is a class in the core). I then looped over all cells to create a string which contained the html for creating a table with the values of my board. This is the body for the response. Now when ever someone sends a request to the server such as refreshing the page the board will be displayed. I set the text for each cell as a href which redirected the user to a URL which contained the move information. For example if someone pressed the cell number 1; it would redirect them to “/move=1”. When the server gets a request and invokes the call method, it calls it with a hash of the request data. From this data we can get the query string which in this case would be “/move=1”. We can then parse this string using CGI (The Common Gateway Interface) a static class included in Ruby. When we parse this query string it will return an hash containing keys and values, in our case:

CGI.parse("/move=1") => {"move" => ["1"]}

Now we can mark the Board in the correct position. This was as far as I went with the spike. I then started again, but this time with TDD.