So you have tested server logic in Ruby, and a working front-end prototype. What is the easiest way to hook them up?
I had some experience with Ruby on Rails so I first generated a rails app to handle the backend. A large directory structure filled with boilerplate appeared, Turbolinks broke my event handlers, and I decided a microframework like Sinatra was much better suited to the task.
Run this in your project directory
gem install sinatra
Move your frontend
- public (index.html)
- js (app.js, jquery.min.js, bootstrap.min.js)
- css (app.css, bootstrap.css)
- fonts (Bootstrap glyphicons)
Create a controller.rb in the root to serve it all up
And fire it up using
Webrick should be fired up and serving index.html on http://localhost:4567/
Add the New Game action
How do we keep the multiple games running on the server apart?
Add the securerandom gem, and add a read-only id property on our Game object:
We need to store this game object between requests, and we’re not going to use a database for this. Instead, we’ll set up a hash in Sinatra’s configuration when the app loads:
In your app.js, your reset function should request a new game:
Your server creates, stores and returns the new game:
Back on the client, your onGameCreated function should extract the id and store it for future requests
Restart your sinatra host, and you should see an AJAX request going out to your server as soon as the page hits your reset() method.
Add the Guess action
Once the player has selected four colors I allow then to submit the guess. See here the use of gameId, and colors is passed as an array in the POST payload.
Your web handler should look something like this:
Things I think are great about this code:
- You can pull params from the requested URL or the postdata
- The RESTful method signature is very descriptive: Post this guess to the guesses of the game identified by id.
Only the converting of strings to symbols is a bit unproductive.
Deploy to a server
Because I don’t want to set up my own server, and Platform-as-a-Service providers often have restricted free accounts, we will deploy the app to Heroku.
Their Getting Started page walks you through signing up, installing the client tools and deployment. Once you’re ready to deploy, check the rest of this blog post.
Using their instructions for Rack apps we will set up the Gemfile and config.ru in the root:
You should have run heroku login at this point, so we are ready to create and deploy the app using a git push:
heroku create git push heroku master heroku open
You should be up and running! The free Heroku instances tend to go to sleep every once in awhile. If the app is still running, the url is at: Tom’s MasterMind