Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create an executable for a Gem using Rake

Tags:

ruby

rake

gem

What is the best way to create an executable (a file in the bin/ directory) for a Gem using Rake? I have a gem that I want to make an executable for and I'm not quite sure how to actually create the executable.

like image 530
Mark Szymanski Avatar asked Mar 14 '11 02:03

Mark Szymanski


2 Answers

You shouldn't need to generate your gem's executables. Ideally, your executable depends upon the library that your gem provides for functionality. For example, take a look at the heroku executable in the Heroku gem:

#!/usr/bin/env ruby

lib = File.expand_path(File.dirname(__FILE__) + '/../lib')
$LOAD_PATH.unshift(lib) if File.directory?(lib) && !$LOAD_PATH.include?(lib)

require 'heroku'
require 'heroku/command'

args = ARGV.dup
ARGV.clear
command = args.shift.strip rescue 'help'

Heroku::Command.run(command, args)

It's the minimum amount of code necessary to parse the command line and ship that data off to the rest of the Heroku library for processing. No need for generating anything when the code changes, because the executable itself depends on the code to function.

like image 142
Michelle Tilley Avatar answered Nov 02 '22 07:11

Michelle Tilley


If you want to create the executable using ruby, the keyword you're looking for is Shebang

Simply create a file (bin/yourexecutable), drop the ".rb" extension if you want, add the Shebang on top, using /usr/bin/env ruby and have at it.

#!/usr/bin/env ruby
puts "hello world"

Give it an executable flag via chmod +x bin/yourexecutable and you can launch it by calling it directly.

varar:~ mr$ bin/yourexecutable
hello world
varar:~ mr$

Check the Wikipedia page for more info.

Obviously, this won't work on Windows.

like image 26
fx_ Avatar answered Nov 02 '22 09:11

fx_