Adding code revision header to your apps
Posted on 25 Jan 2012
Sometimes its necessary to have a code revision tag somewhere on the website. Use cases are usually different and vary from just checking against the current revision, automatic upgrades and such.
If you’re rolling deployments with capistrano, it will insert the REVISION file under the app’s root dir with git sha or svn revision or whatever tag based on SCM of your choice.
Here is the simple rack middleware that injects that revision as a ‘X-REVISION’ header in responses.
module Rack
class Revision
@@revision = nil
File = ::File
def initialize(app, &block)
@app = app
@block = block
@file = File.join(Dir.pwd, 'REVISION')
end
def call(env)
status, headers, body = @app.call(env)
headers['X-Revision'] = revision
[status, headers, body]
end
protected
def revision
@@revision ||= read_revision
end
def read_revision
File.exists?(@file) ? File.read(@file).strip : 'UNDEFINED'
end
end
end
For instance, just put that file as lib/rack/revision.rb
and change your config.ru file:
require ::File.expand_path('../config/environment', __FILE__)
use Rack::Revision
run YOUR_APP::Application
You’ll need to restart the app to apply the changes.
To test if it works just run:
curl -i -X HEAD "http://YOUR_WEBSITE/"
Sample output would be:
ETag: "8d6228d86642025c31e3d54e9a67b14b"
Cache-Control: max-age=0, private, must-revalidate
X-Runtime: 0.001491
X-Rack-Cache: miss
X-Revision: f8c51630843898e88848261dd5ebac3fdebc5e48