Ruby:在包含时存储值

Ruby:在包含时存储值,ruby,metaprogramming,class-variables,Ruby,Metaprogramming,Class Variables,在Ruby类中,我希望在包含给定模块时存储变量的值。下面是一个人为的例子: module M def self.included(base) base.class_eval do @@inclusion_time = Time.now def included_at @@inclusion_time end end end end class A include M end sleep 3 class B

在Ruby类中,我希望在包含给定模块时存储变量的值。下面是一个人为的例子:

module M
  def self.included(base)
    base.class_eval do
      @@inclusion_time = Time.now

      def included_at
        @@inclusion_time
      end
    end
  end
end

class A
  include M
end

sleep 3

class B
  include M
end

sleep 3

class C
  include M
end

a = A.new
b = B.new
c = C.new

puts a.included_at
puts b.included_at
puts c.included_at
我尝试过很多方法(attr\u访问器、set\u常量等),但最终结果总是一样的。所有类都具有上次设置的值


如何解决这个问题?

当我将SO的模块M替换为您的模块M时,
A.new.included\u at
返回nil(当然,B和C相同),而
def self.included(klass)klass.instance\u variable\u set(:@include\u time,time.now)end
给出了所需的结果。请注意,在包含的self.included中,self等于M。
module M
  def self.included _
    @inclusion_time = Time.now
  end
  def included_at
    self.class.instance_eval{@inclusion_time}
  end
end