Ruby - 方法集合

Ruby - collection of methods

我继承了一堆没有被任何 类 或模块包装的方法,只是列在一个 .rb 文件中。由于在 Cucumber 测试套件中使用了该文件,因此这成为可能。我想收集所有这些方法并迭代每个方法调用,在调用它们时对每个方法做一些工作。

例如:

def call_all_methods
  method1
  method2
  method3(true)
  method3(false)
  method4('Y', true)
  method4('N', true)
  method4('Y', false)
  method4('N', false)
end

我想做的是将它们全部包装在一个数组中,然后用 begin/rescue 块围绕它们单独调用它们

$all_methods.each do |method|
  begin
    method.call
  rescue Exception1
    handle_exception1
  rescue Exception2
    handle_exception2
  end
end

我试过使用 %w

将它们全部放在一个数组中
call_all_methods = %w(...)

这行得通,但它使 IDE

中的方法难看

我试过对文件执行 readlines,但是在读取文件时执行了这些方法。

我可以创建方法来包装每个调用,但是我有一个方法可以调用另一个方法(一行),这也不正确。

我看过 但这些解决方案似乎都不是我想要做的事情的好解决方案,因为它会弄脏代码

你可以这样做:

def execute_several(arr)
  arr.each do |method, *args|
    begin
      v = send(method, *args)
      puts "for method '#{method}': #{v}"
    rescue ArgumentError => e
      puts "for method '#{method}': #{e.message}"
      end
    end
  end

  arr = [
    [:class],
    [:rand, 20],
    [:Integer, "20"],
    [:Integer, 'cat']
  ]

  execute_several(arr)
    # for method 'class': Object
    # for method 'rand': 17
    # for method 'Integer': 20
    # for method 'Integer': invalid value for Integer(): "cat"

这是一个如何在 class 中完成的示例:

class Array
  def execute_several(arr)
    arr.each do |method, args|
      begin
        v = args ? send(method, args) : send(method)
        puts "for method '#{method}': #{v}"
      rescue TypeError => e
        puts "for method '#{method}': #{e.message}"
      end
    end
  end
end

arr = [
  [:reverse],
  ['first'],
  [:&, [2,3,4]],
  [:|, 'cat']
]

[1,2,3].execute_several(arr)
  # for method 'reverse': [3, 2, 1]
  # for method 'first': 1
  # for method '&': [2, 3]
  # for method '|': no implicit conversion of String into Array

如果我正确理解您的问题,您可以将这些方法包装在 class.

class MyMethods
    # all those methods that you have in that file
end

然后您可以通过

将它们全部列出

all_methods = MyMethods.instance_methods(false)

要执行它们,你可以all_methods.each {|m| MyMethods.new.send(m)}

我最终制作了一系列 procs