Skip to content

Instantly share code, notes, and snippets.

@dragonfax
Created March 12, 2013 21:00
Show Gist options
  • Save dragonfax/5146987 to your computer and use it in GitHub Desktop.
Save dragonfax/5146987 to your computer and use it in GitHub Desktop.
Boilerplate for a script that runs from anywhere without installing it as a gem.

To enable a script to

  • from its project directory
  • run from anywhere on the system.
  • from inside or outside its project directory
  • with its own lib directory
  • with a Gemfile (bundler)
  • with symlinks to it from various places like /usr/local/bin
  • with a garuanteed ruby version
  • with rvm, but without having to run rvm use each session.

Why not just install it as gem, and have most of this taken care of for you?

#!/usr/bin/env rvm 1.9.3 do ruby

## check ruby version
# we require 1.9.3 but some of our hosts have rvm default to ree
require 'rubygems'
ruby_ver = Gem::Version.new(RUBY_VERSION.dup)
desired_ver = Gem::Version.new('1.9.3')
raise "must be using ruby version 1.9.3 or higher" if ruby_ver < desired_ver

# Pathname.realpath resolves the symlink we're using in /usr/local
require 'pathname'
SCRIPT_DIR = Pathname.new(__FILE__).realpath.dirname.to_s

## bundler setup
# we want to call this script from outside the project
ENV['BUNDLE_GEMFILE'] = SCRIPT_DIR + '/../../Gemfile'
require 'bundler/setup'

## add our lib.
# since we're not using gem to do it for us.
# Pathname again, because we may be called via a symlink
require 'pathname'
$LOAD_PATH << SCRIPT_DIR + '/../lib'

<rest of the script here>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment