Setting an option in a call to a Ruby module function

208 Views Asked by At

Consider this snippet from Ruby's open4:

  def spawn arg, *argv
    argv.unshift(arg)
    opts = ((argv.size > 1 and Hash === argv.last) ? argv.pop : {})
    argv.flatten!
    cmd = argv.join(' ')


    getopt = getopts opts

    ignore_exit_failure = getopt[ 'ignore_exit_failure', getopt['quiet', false] ]
    ignore_exec_failure = getopt[ 'ignore_exec_failure', !getopt['raise', true] ]
    exitstatus = getopt[ %w( exitstatus exit_status status ) ]
    stdin = getopt[ %w( stdin in i 0 ) << 0 ]
    stdout = getopt[ %w( stdout out o 1 ) << 1 ]
    stderr = getopt[ %w( stderr err e 2 ) << 2 ]
    pid = getopt[ 'pid' ]
    timeout = getopt[ %w( timeout spawn_timeout ) ]
    stdin_timeout = getopt[ %w( stdin_timeout ) ]
    stdout_timeout = getopt[ %w( stdout_timeout io_timeout ) ]
    stderr_timeout = getopt[ %w( stderr_timeout ) ]
    status = getopt[ %w( status ) ]
    cwd = getopt[ %w( cwd dir ) ]

Suppose now that I would like to make ignore_exit_failure == true when calling this function from code that uses the gem. How would I do that?

EDIT: I guess I had just assumed the getopts thing was a standard Ruby module thing for passing options around. Here is the definition of getopts per Alex Kliuchnikau's comment:

  def getopts opts = {}
    lambda do |*args|
      keys, default, ignored = args
      catch(:opt) do
        [keys].flatten.each do |key|
          [key, key.to_s, key.to_s.intern].each do |key|
            throw :opt, opts[key] if opts.has_key?(key)
          end
        end
        default
      end
    end
  end
  module_function :getopts

Perhaps this is just a question for someone already familiar with the open4 module.

1

There are 1 best solutions below

3
Aliaksei Kliuchnikau On

You need to pass parameters this way:

open4.spawn cmd, 'ignore_exit_failure' => true

If you don't specify it, it will set ignore_exit_failure to the value of quiet parameter.

open4.spawn cmd, 'quiet' => true

And if it is not specified as well, it will set ignore_exit_failure to false.