开发者

How can a module define a static property that is not shared between different classes that include it?

If I define a module like this:

module M
   @@p = []

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

   def show_p
       @@p
   end
end

then every class that includes the module will have the same @@p array:

class A
   include M
end
class B
   include M
end

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

B.new.show_p

?> ["a", "b"]

Is it possible to define a unique static property for each individu开发者_如何学运维al class that includes the module, so the classes don't interfere with each other? i.e. so I can do this:

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

A.new.show_p

?> "a"

B.new.show_p

?> "b"

Thanks!


Instead of creating a static property, define a property on the class object itself:


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


Output:

["a"]
["b"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜