似乎实例方法FileUtils
都是私有的(如另一个答案中所述,这意味着它们只能在没有显式接收器的情况下调用)。当你包含或扩展时,你得到的是实例方法。例如:
require 'fileutils'
class A
include FileUtils
end
A.new.pwd #=> NoMethodError: private method `pwd' called for #<A:0x0000000150e5a0>
o = Object.new
o.extend FileUtils
o.pwd #=> NoMethodError: private method `pwd' called for #<Object:0x00000001514068>
事实证明,我们想要的所有方法FileUtils
都存在两次,作为私有实例方法和公共类方法(也称为单例方法)。
基于这个答案,我想出了这段代码,它基本上将所有类方法从复制FileUtils
到FileManager
:
require 'fileutils'
module FileManager
class << self
FileUtils.singleton_methods.each do |m|
define_method m, FileUtils.method(m).to_proc
end
end
end
FileManager.pwd #=> "/home/scott"
它不漂亮,但它可以完成工作(据我所知)。