2017-09-30 40 views
0

我有一個文件SomethingClass.rb看起來如下:如何在Ruby中將文件作爲模塊的一部分?

class SomethingClass 
    def initialize 
    puts "Hello World" 
    end 
end 

我想require文件SomethingClass.rb,使模塊SomethingModuleSomethingClass部分,而不改變文件。

此外,我想避免使SomethingClass模塊外的部分名稱空間。換句話說,我想require該文件和我的應用程序的其餘部分不應該改變的事實,即SomethingModule將被定義。

這不起作用(我假設,因爲requireKernel範圍內執行):

module SomethingModule 
    require './SomethingClass.rb' 
end 

這可能在Ruby中?

+2

除非我誤解了這個問題,這似乎並不有什麼做用含有類定義是一個文件在另一個文件中需要。假設你有一個文件定義了一個類和一個模塊(不是模塊中的類)。我相信你希望在不改變類定義的情況下將類移到模塊中。那是對的嗎?如果是這樣,這個問題的本質是什麼? –

+0

@CarySwoveland是的,這是正確的。我用'require'問了這個問題,因爲這是我打算使用它的方式。我不確定使用'require'是否可以使解決方案成爲可能,而不是將類移動到模塊。 – PawkyPenguin

回答

1

不改變你的類文件,從我收集到的,只有一種哈希方式來做到這一點 - 見Load Ruby gem into a user-defined namespaceHow to undefine class in Ruby?

但是我認爲如果你允許自己修改類文件,它會更容易一些。可能是最簡單的做法是將原來的類名設置的東西,一定會沒有名字衝突,例如:

class PrivateSomethingClass 
    def initialize 
    puts "Hello World" 
    end 
end 

module SomethingModule 
    SomethingClass = PrivateSomethingClass 
end 

現在你對全局命名空間中定義SomethingModule::SomethingClass但不SomethingClass

另一種方式來做到這一點是使用一個工廠方法和anonymous class

class SomethingClassFactory 
    def self.build 
    Class.new do 
     def initialize 
     "hello world" 
     end 
    end 
    end 
end 

module SomethingModule 
    SomethingClass = SomethingClassFactory.build 
end 
相關問題