2011-01-20 3 views
0

私はこのようなモジュールを定義した場合:モジュールは、それを含む異なるクラス間で共有されない静的プロパティをどのように定義できますか?

class A 
    include M 
end 
class B 
    include M 
end 

A.add "a" 
B.add "b" 

B.new.show_p 

?> ["a", "b"] 

の一意の静的プロパティを定義することが可能です:

module M 
    @@p = [] 

    def self.included(base) 
     def base.add(a) 
      @@p += a 
     end 
    end 

    def show_p 
     @@p 
    end 
end 

を、モジュールが含まれ、すべてのクラスが同じ@@ p個の配列がありますがモジュールを含む個々の各クラスは、クラスが互いに干渉しないようにします。つまり、私はこれを行うことができます:

A.add "a" 
B.add "b" 

A.new.show_p 

?> "a" 

B.new.show_p 

?> "b" 

ありがとう!代わりに、静的プロパティを作成する

答えて

0

、クラスオブジェクト自体のプロパティを定義します。

 

module Foo 
    def self.included(base) 
    base.instance_variable_set(:@p, []) 
    class << base 
     attr_reader :p 
     def add(a) 
     @p << a 
     end 
    end 
    end 
end 

class First 
    include Foo 
end 

class Second 
    include Foo 
end 

require 'pp' 
First.add "a" 
Second.add "b" 
pp First.p 
pp Second.p 

 

出力:

 
["a"] 
["b"] 
+0

感謝。 'instance_variable_set 'は私が探していたものです。 –

+0

しかし、どうすればインスタンスからアクセスできますか? f = First.new; f.class.p; この種の作品。しかし、私が最初に拡張した場合、動作しません。 –

+0

@Peterたとえば、x.class.p。 – adamax

関連する問題