Module: Nuggets::File::WhichMixin

Included in:
File
Defined in:
lib/nuggets/file/which_mixin.rb

Constant Summary collapse

DEFAULT_EXTENSIONS =
[::RbConfig::CONFIG['EXEEXT']]

Instance Method Summary collapse

Instance Method Details

#which(executable, extensions = DEFAULT_EXTENSIONS) ⇒ Object

call-seq:

File.which(executable[, extensions]) => aString or +nil+

Returns executable if it’s executable, or the full path to executable found in PATH, or nil otherwise. Checks executable with each extension in extensions appended in turn.

Inspired by Gnuplot.which – thx, Gordon!



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/nuggets/file/which_mixin.rb', line 43

def which(executable, extensions = DEFAULT_EXTENSIONS)
  extensions |= ['']

  if env = ::ENV['PATH']
    dirs = env.split(self::PATH_SEPARATOR)
    dirs.map! { |dir| expand_path(dir) }
  end

  extensions.find { |extension|
    file = "#{executable}#{extension}"
    return file if file?(file) && executable?(file)

    dirs.find { |dir|
      path = join(dir, file)
      return path if file?(path) && executable?(path)
    } if dirs
  }
end

#which_command(commands, extensions = DEFAULT_EXTENSIONS) ⇒ Object

call-seq:

File.which_command(commands) => aString or +nil+

Returns the first of commands that is executable (according to #which).



66
67
68
# File 'lib/nuggets/file/which_mixin.rb', line 66

def which_command(commands, extensions = DEFAULT_EXTENSIONS)
  commands.find { |command| which(command.to_s[/\S+/], extensions) }
end