Sunday, November 20, 2011

Rake file for a sinatra app on Cloud Foundry

My boss is on his money moon, next week is thanks giving, there is no fire to put out and the baby is sleeping - which means I had some time to catch up with my personal todo list today! One thing on it is a simple sinatra app which I wil deploy to Cloud Foundry later.
Exactly what the app is about isn't important, but rather how to get started with it. Note that I'm skipping over all BDD & TDD for now...
Usually I start with something simple like this:
Gemfile
source "http://rubygems.org"

gem 'sinatra'
app.rb
require 'sinatra'

get '/' do
  "It works!"
end
Then I run bundle to grab any missing gems, and then run ruby app.rb to start the app, and finally I verify that it works with curl localhost:4567
If everything turns out ok, I'll deploy the app on Cloud Foundry with:
vmc push -n cf-rake-sinatra
Creating Application: OK
Uploading Application:
  Checking for available resources: OK
  Packing application: OK
  Uploading (1K): OK
Push Status: OK
Staging Application: OK
Starting Application: OK
Now I can verify that this works too, using curl cf-rake-sinatra.cloudfoundry.com. Once this initial deploy is done, I'll run vmc update cf-rake-sinatra each time I change the app. Sometimes I add a new gem dependency, and it has happened more than once that I forget to run bundle, so I've created a Rakefile with two of commonly used tasks:
Rakefile
APP = "cf-rake-sinatra"

$:.unshift(File.dirname(__FILE__))

task :default => [:run]

desc "run app locally"
task :run => "Gemfile.lock" do
  require 'app'
  Sinatra::Application.run!
end

# need to touch Gemfile.lock as bundle doesn't touch the file if there is no change
file "Gemfile.lock" => "Gemfile" do
  sh "bundle && touch Gemfile.lock"
end

namespace :vmc do
  desc "update cloud foundry deployment"
  task :update => "Gemfile.lock" do
    sh "vmc update #{APP}"
  end

  desc "get application status"
  task :status do
    sh "vmc stats #{APP}"
  end
end
This will run bundle any time Gemfile is newer than Gemfile.lock so that we always have up to date gems.
The full list of available rake tasks are:
rake -T
(in /Users/martin/src/ruby/cf-rake-sinatra)
rake run         # run app locally
rake vmc:status  # get application status
rake vmc:update  # update cloud foundry deployment

No comments:

Post a Comment