Making Ruby Gems executable from terminal : Standalone

I presume you have developed a ruby gem. Its working fine when required to another ruby application. Now you want to make it standalone and running from terminal.

Wondering how to do that?

Its preety simple and straight forward way. All stuffs are done by the bundler itself. You just need to configure it properly.

It was different in older bundler version.. but now it works like this

In you_gem.gemspec

# it tells bundler that all executable files are inside `exe` dir
#   see http://bundler.io/blog/2015/03/20/moving-bins-to-exe.html
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }

 

So you need to keep all of your executables inside `exe` folder and sample exe file looks like. the file name is just ‘hulaki‘ with no extension.

#!/usr/bin/env ruby
# encoding: UTF-8
# exe/hulaki

# $: is just a shortcut for $LOAD_PATH. __FILE__ is the relative 
#   path to the script. This adds the current script directory 
#   to the load path
this_file = Pathname.new(__FILE__).realpath
$:.unshift File.expand_path("../../lib", this_file)
require 'hulaki'

Sources:

http://bundler.io/blog/2015/03/20/moving-bins-to-exe.html

http://stackoverflow.com/questions/9238367/ruby-unshift-file-dirname-file

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s