gpt4 book ai didi

ruby - 如何选择要在 Ruby 中动态包含的模块版本?

转载 作者:数据小太阳 更新时间:2023-10-29 06:46:46 28 4
gpt4 key购买 nike

我正在编写一个使用 fileutils 的小型 Rub​​y 命令行应用程序来自文件操作的标准库。根据用户调用应用程序的方式,我想包括 FileUtils , FileUtils::DryRunFileUtils::Verbose .

include虽然是私有(private)的,但我无法将选择逻辑放入对象的 initialize 中方法。 (这是我的第一个想法,从那时起我就可以将有关用户选择的信息作为参数传递给 new 。)我想出了两个似乎可行的选项,但我对其中任何一个都不满意:

  1. 根据用户的选择在应用程序的命名空间中设置一个全局变量,然后在类中执行条件包含:

    class Worker
    case App::OPTION
    when "dry-run"
    include FileUtils::DryRun
    etc.
  2. 创建子类,唯一的区别是 FileUtils 的版本他们包括。根据用户的选择,选择合适的。

    class Worker
    include FileUtils
    # shared Worker methods go here
    end
    class Worker::DryRun < Worker
    include FileUtils::DryRun
    end
    class Worker::Verbose < Worker
    include FileUtils::Verbose
    end

第一种方法看起来很枯燥,但我希望有一些我没有想到的更直接的方法。

最佳答案

如果它是私有(private)的呢?

class Worker
def initialize(verbose=false)
if verbose
(class <<self; include FileUtils::Verbose; end)
else
(class <<self; include FileUtils; end)
end
touch "test"
end
end

这包括 FileUtils::something 特别是 Worker 的元类——不在主 Worker 类中。不同的工作人员可以通过这种方式使用不同的 FileUtils

关于ruby - 如何选择要在 Ruby 中动态包含的模块版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3358601/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com