好像實例方法上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
是有方法的兩倍,爲私有實例方法,也可以作爲公共類方法(又稱單方法)。
基於this answer我想出了這個代碼基本上將所有類方法從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"
這不是很漂亮,但它的工作(據我可以告訴)。
http://stackoverflow.com/questions/4662722/extending-a-ruby-module-in-another-module-including-the-module-methods http://stackoverflow.com/questions/1655623/ ruby-class-c-includes-module-m-including-module -n-in-m-does-not-affect-c-what –
感謝Robert,我已經看過'included'模式,但自從'FileUtils ''裏面沒有'ClassMethods'類型的模塊,我認爲這不是合理的。第二個鏈接看起來可能更接近我正在尋找的東西。 – webdesserts