Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

Wrapping a UNIX / Linux / OS X Binary in Ruby

I'm creating a basic gem that wraps UNIX / Linux / OS X command and wanted to ensure the PATH is correctly loaded (i.e. when running under passenger for a ruby-on-rails app it have '/usr/bin'). Here is a simple example to illustrate what I'm trying to do (the actual example is more complicated):

module Silly
  def self.tail(path)
    `tail #{path}`
  end
end

Should and/or can I add common folders to the PATH in ruby? If not, is it OK to directly reference /usr/bin/tail (or any other binaries in that directory) or will they be located in different directories on different systems? Thanks!

Upvotes: 0

Views: 338

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

On Linux and Mac OS you can ask the OS to tell you where the preferred version of a particular command is, using which. For instance:

Greg:stackoverflow greg$ which ls
/bin/ls
Greg:stackoverflow greg$ which find
/usr/bin/find
Greg:stackoverflow greg$ which ruby
/Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/ruby

Notice that it picked up MY preference for Ruby, not the one that is in /usr/bin or /usr/local/bin. That's important because a user, or system administrator might have a very valid reason for installing a new version of a command, aliasing or soft-linking something else or removing it. If you assume you know better than they do, you could end up executing an old and buggy version or ignoring the user's preferred environment.

If you're familiar with Perl, the CPAN app does a lot of environment sensing as its configuring the defaults, but it always asks if its default, determined through discovery, is correct and allows the user to change or delete it. It also knows alternate apps for similar functionality, such as using ftp, nftp or wget for retrieving files. Some commands are not available across OSes. Even flavors of Unix and/or Linux can vary. Toss in MacOS, Cygwin and other Unix-like environments and you will find a number of different names for kind of the same functionality.

Upvotes: 1

Josh Lee
Josh Lee

Reputation: 177550

You can access environment variables with the ENV global hash, so ENV['PATH'] = ENV['PATH'] + ':/usr/bin' for example. It might be possible to invoke commands with /bin/sh, since that might set the path automatically.

Upvotes: 2

Related Questions