Tag: 包含

Ruby模块,带有来自includer类的静态方法调用

我需要在模块中定义使用包含此模块的类中的方法的常量: module B def self.included(base) class << base CONST = self.find end end end class A def self.find "AAA" end include B end puts A::CONST 但是编译器会在第4行给出错误。 有没有其他方法来定义常量?

如何选择在Ruby中动态包含哪个版本的模块?

我正在编写一个小型的Ruby命令行应用程序,它使用标准库中的fileutils进行文件操作。 根据用户调用应用程序的方式,我将要包括FileUtils , FileUtils::DryRun或FileUtils::Verbose 。 既然include是私有的,我不能把逻辑选择到对象的initialize方法中。 (这是我的第一个想法,从那时起我就可以将有关用户选择的信息作为参数传递给new 。)我已经提出了两个似乎有用的选项,但我对以下两种方法都不满意: 根据用户的选择在应用程序的命名空间中设置一个全局变量,然后在类中执行条件包含: class Worker case App::OPTION when “dry-run” include FileUtils::DryRun etc. 创建子类,唯一的区别是它们包含哪个版本的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 第一种方法似乎是DRY-er,但我希望有一些我没有想到的更简单的方法。