2011-07-19 2 views
5

:中Rubyはネストされたクラスの継承をどのように扱いますか?次のテストケースで

class Package 
    class Component 
     def initialize 
      p [:initialize,self] 
     end 
    end 
end 

class Package_A < Package 
end 

class Package_B < Package 
end 

# Why are the following components of type Package and not Package_A and Package_B 
component=Package_A::Component.new 
p component 

component=Package_B::Component.new 
p component 

結果:

[:initialize, #<Package::Component_1:0x2c0a8f8>] 
#<Package::Component:0x2c0a8f8> 
[:initialize, #<Package::Component_1:0x2c0a5b0>] 
#<Package::Component:0x2c0a 

はどのようにして、特定のPackage_A.componentとPackage_B.componentを得るのですか?

答えて

6

クラスComponentPackageに記載されているため、正しく表示されます。 ::は、Package_Aの範囲内で名前Componentを検索するよう指示します。そこにはComponentが存在しないので、スーパークラスを検索します。

この例では、目的を達成する方法を示します。よりシンプルな方法があるかもしれませんが、私はそれを見て満足しています。

class Package 
    class Component 
    def foo 
     puts "bar" 
    end 
    end 
end 

class Pack_a < Package 
end 

Pack_a::Component.new.foo 
#=> bar 
# as expected, though we actually have Package::Component 

class Pack_b < Package 
    class Component 
    end 
end 

Pack_b::Component.new.foo 
#=> NoMethodError: undefined method 'foo' for Pack_b::Component 
# this error is because Pack_b::Component has nothing to do with Package::Component 

class Pack_c < Package 
    class Component < Package::Component 
    end 
end 

Pack_c::Component.new.foo 
#=> bar 
# as expected 

Pack_c::Component.new 
#=> Pack_c::Component 
# this Component is a subclass of Package::Component 

これは、このような場合にスコープがどのように機能するかを説明するものです。お役に立てれば。

+0

上記の例のおかげで@スロー...私はアプリケーションの問題を解決するために使用しました。おそらく誰かがクラス1、クラス2 inheritable_nested_class ** を支援しようと... ** 例:ディレクティブは言って、これは上記の定型につながるコンポーネント inheritable_nested_class自動的にクラスから継承するサブクラスで生成されています。それは高度なメタプログラミングクラスで素敵な割り当てをするでしょう:-) – DMisener

関連する問題