2013-12-13 53 views
0

在Ruby類中,我想在包含給定模塊時存儲變量的值。下面是一個人爲的例子: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_accessor,set_constant,等),但最終的結果總是相同的。所有的類都有最後設定的值。

我該如何解決這個問題?

回答

2
module M 
    def self.included _ 
    @inclusion_time = Time.now 
    end 
    def included_at 
    self.class.instance_eval{@inclusion_time} 
    end 
end 
+0

當我與你替換SO的組件M,'A.new.included_at'返回nil(同樣爲B和C,當然),而'DEF self.included(克拉斯)klass.instance_variable_set(:@ inclusion_time,Time.now)end'給出期望的結果。請注意,在'self.included'內,自我等於M. –