Konstantin
Konstantin

Reputation: 3123

A library that can be loaded/required as well as be used as a program

I would like to write a small Ruby library. Sometimes I want to use it as a standalone CLI application, and sometimes as a loadable library. How can I achieve this?

Upvotes: 0

Views: 24

Answers (1)

sawa
sawa

Reputation: 168081

If it is going to be a simple file, the common way is:

#!/usr/bin/env ruby

# content of the library
...

if $0 == __FILE__
  # command to be executed only when the file is called by a command
end

If you want to make it a gem, the standard way is to write the executable Ruby script in a file (let's say foo) under the /bin directory within the gem directory, and add the following to the *.gemspec file:

Gem::Specification.new do |s|
  ...
  s.executables << "foo"
  ...
end

Upvotes: 1

Related Questions