Hommer Smith
Hommer Smith

Reputation: 27862

How can I run a Ruby gem from the shell?

Say I have a gem that transforms from Celsius to Fahrenheit. So, from within my IRB, and after the gem is installed, I can do:

Temperature.convert_to_celsius(80)

My question is, how do you modify a gem in order for it to be able to be run from the shell? I have seen some gems that have a bin folder, but I am not sure how to proceed. What is the proper way of doing so?

Upvotes: 2

Views: 529

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84443

Write Your Own Wrapper Script

You're over-thinking this. A gem is just a packaged Ruby module. Most gems have executable Ruby scripts that allow one to run them from the command line, but some don't, especially if they're intended to be used as libraries instead of commands. If your gem doesn't have its own executable wrapper, you can write your own.

Assuming your gem is called something like "temperature," you could simply write an executable Ruby wrapper named temp.rb like so:

#!/usr/bin/env ruby

require 'temperature'
Temperature.convert_to_celsius ARGV.first

Put the wrapper somewhere in your PATH (e.g. $HOME/bin), and make sure the script is executable (e.g. chmod 755 ~/bin/temp.rb). Then you can call the script from the command line:

$ temp.rb 80
26.6667

Upvotes: 3

Related Questions