检查Ruby代码中的命令行参数是否存在

时间:2018-08-24 11:55:31

标签: ruby

如果存在命令行参数,我想执行Ruby代码:

ruby sanity_checks.rb --trx-request -e staging_psp -g all

Ruby代码:

def execute
    command_options = CommandOptionsProcessor.parse_command_options
    request_type    = command_options[:env]
    tested_env      = command_options[:trx-request]   // check here if flag is present
    tested_gateways = gateway_names(env: tested_env, gateway_list: command_options[:gateways])
    error_logs      = []

   if(request_type.nil?)
    tested_gateways.each do |gateway|
      ........
    end
   end

    raise error_logs.join("\n") if error_logs.any?
  end

如何获取参数--trx-request并检查其是否存在?

编辑:

命令解析器:

class CommandOptionsProcessor

  def self.parse_command_options
    command_options = {}
    opt_parser = OptionParser.new do |opt|
      opt.banner = 'Usage: ruby sanity_checks.rb [OPTIONS]'
      opt.separator  "Options:"

      opt.on('-e TEST_ENV', '--env TEST_ENV','Set tested environment (underscored).') do |setting|
        command_options[:env] = setting
      end

      opt.on('-g X,Y,Z', '--gateways X,Y,Z', Array, 'Set tested gateways (comma separated, no spaces).') do |setting|
        command_options[:gateways] = setting
      end
    end

    opt_parser.parse!(ARGV)

    command_options
  end
end

你能建议吗?

1 个答案:

答案 0 :(得分:2)

您将需要像这样向您的OptionParser添加一个布尔开关选项

opt.on('-t','--[no-]trx-request','Signifies a TRX Request') do |v|
  # note we used an underscore rather than a hyphen to make this symbol 
  # easier to access
  command_options[:trx_request] = v 
end

然后在您的execute方法中,您可以通过

进行访问
command_options[:trx_request]

如果需要默认值,可以在parse_command_options之外的OptionParser方法中添加一个默认值,将其设置为command_options[:trx_request] = false