How To: Add current commit to Rails template

I wanted to add the current revision of a Rails project to my layout so I can easily know what version the current code base is running. I came up with a short initializer that can be added to define a global constant for the commit id and commit timestamp.

# RAILS_ROOT/config/initializers/tag_revision.rb
# Call +git+ and obtain the current commit SHA1 and commit date. Store these values
# in +PROJECT_VERSION_COMMIT_ID+ and +PROJECT_VERSION_COMMIT_DATE+. Then define
# +PROJECT_VERSION+ to be a string of the two.
git_cmd = 'git show --pretty=format:"%H|%ci" --quiet'
commit_id = nil
commit_date = nil
begin
  commit_id, commit_date = IO.popen(git_cmd) {|f| f.gets.split("|") }
rescue Errno::ENOENT # git not available
  commit_id = 'Unknown'
  commit_date = ''
end
unless defined?(::PROJECT_VERSION)
  ::PROJECT_VERSION_COMMIT_ID = commit_id
  ::PROJECT_VERSION_COMMIT_DATE = commit_date
  ::PROJECT_VERSION = "#{commit_id} #{commit_date}"
end
# app/helpers/application_helper.rb
module ApplicationHelper
  def link_to_version
    if ENV['RAILS_ENV'] == 'development'
      link_to PROJECT_VERSION, "http://subdomain.unfuddle.com/repositories/commit/#{PROJECT_COMMIT_ID}"
    else
      PROJECT_VERSION
    end
  end
end
# app/views/layout/application.html
....
<div id="footer"> <%= link_to_version %> </div>

When the application is run in development mode, a link will appear in the footer to the hosted repository. I’m using Unfuddle for my project but you can obviously return anything you want in the helper.

This entry was posted in Programming, Rails, Ruby. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>