Saturday, June 28, 2014

Sinatra extensions

I have been working on a web-based blackjack game as an assignment for Tealeaf Academy's first course. The program is written in Sinatra, a Ruby based language for web applications.

As the application gets larger, it becomes inconvenient to keep all Sinatra routes and helper methods in the application's main.rb file. The example below shows how to move functionality from main.rb into another file using Sinatra extensions.

One of the first tasks the application performs is to prompt for, read, and save the player's name. The prompt is issued in response to an HTTP GET request, and the input is submitted via a POST. It would be convenient to move the Sinatra routes corresponding to these requests to a file called name_handler.rb.

I create this file in the root directory. In this file, I write a module that contains these routes and register the module with Sinatra. The contents of the file are given below. Note that the routes themselves are defined in lines 10-18.

I then include name_handler.rb in the application by adding at the top of the main.rb file. The routes will now act as though they were defined in main.rb.