2012-08-09 61 views
4

在Ruby中,我可以將模塊/類嵌套到其他模塊/類中。我想要的是在文件或類中添加一些聲明,以便能夠通過短名稱引用嵌套類,例如使用Inner得到Outer::Inner,就像你要用Java,C#等語法可能是這樣的:如何在Ruby中將嵌套類「導入」當前類?

module Outer 
    class Inner; end 
    class AnotherInner; end 
end 
class C 
    import Outer: [:Inner, :AnotherInner] 
    def f 
    Inner 
    end 
end 

的簡單的實現可能是這樣的:

class Class 
    def import(constants) 
    @imported_constants = 
     (@imported_constants || {}).merge Hash[ 
     constants.flat_map { |namespace, names| 
      [*names].map { |name| [name.to_sym, "#{namespace}::#{name}"] } 
     }] 
    end 

    def const_missing(name) 
    const_set name, eval(@imported_constants[name] || raise) 
    end 
end 

是否有堅實的實現在Rails或某些gem中,它可以在兼容Rails的自動加載機制的情況下進行類似的導入?

回答

2
module Outer 
    class Inner; end 
    class AnotherInner; end 
end 

class C 
    include Outer 

    def f 
    Inner 
    end 
end 

C.new.f # => Outer::Inner 

記住:有在Ruby中嵌套類沒有這樣的事情。一個類只是一個對象,就像任何其他對象一樣,並且它被賦值爲與其他對象相同的變量。在這種特殊情況下,「變量」是一個在模塊內命名的常量。然後將該常量添加到另一個模塊(或類)的名稱空間,就像您使用其他常量一樣:通過模塊。

+0

我知道這種可能性。雖然1.我不想導入所有的嵌套類。 2.在Rails的上下文中,所有的嵌套類都位於不同的文件中,通常你需要指定'Outer :: Inner',以便Rails知道從哪裏加載它。 – Alexey 2012-08-09 22:03:20