2012-10-24 93 views
2

我正在嘗試製作一個擴展FileUtils類功能的模塊。如何將包含的私有方法公開爲公共類方法?

require 'fileutils' 

module FileManager 
    extend FileUtils 
end 

puts FileManager.pwd 

,如果我跑這一點,我會得到一個錯誤private method 'pwd' called for FileManager:Module (NoMethodError)

更新:
爲什麼這些類的方法包括私下和我如何可以公開所有的他們,而不必在FileManager模塊中手動包含每種方法作爲公共類方法?

+3

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 –

+0

感謝Robert,我已經看過'included'模式,但自從'FileUtils ''裏面沒有'ClassMethods'類型的模塊,我認爲這不是合理的。第二個鏈接看起來可能更接近我正在尋找的東西。 – webdesserts

回答

2

好像實例方法上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我想出了這個代碼基本上將所有類方法從FileUtilsFileManager

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" 

這不是很漂亮,但它的工作(據我可以告訴)。

2
require 'fileutils' 

module FileManager 
    extend FileUtils 

    def FMpwd 
    pwd 
    end 

    module_function :FMpwd 
end 

puts FileManager.FMpwd 

=> /home/rjuneja/Programs/stackoverflow 

這部分是因爲Ruby對待私有和受保護的方法與其他語言略有不同。當一個方法在Ruby中被聲明爲private時,這意味着這個方法永遠不會被明確的接收方調用。任何時候我們可以用隱式接收器調用私有方法,它總是會成功的。您可以在這裏找到更多的信息:

http://www.skorks.com/2010/04/ruby-access-control-are-private-and-protected-methods-only-a-guideline/

爲什麼不猴補丁文件實用程序,包括方法,你想,而不是:

require 'fileutils' 

module FileUtils 
    class << self 
    def sayHello 
     puts "Hello World!" 
    end 
    end 
end 

FileUtils.sayHello 
=> "Hello World!" 
+1

這將要求他用FileUtils的每一個方法來做到這一點,即使只是簡單的迭代也是很乏味的。雖然我喜歡解釋它爲什麼會發生。 –

+0

我同意羅伯特在這裏。我更新了一下我的問題。 – webdesserts

+0

McMullins,爲什麼不擴展FileUtils類呢?檢查我的更新。 – sunnyrjuneja