Ruby:在包含时存储一个值

时间:2013-12-13 03:43:24

标签: 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
  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等),但最终结果始终相同。所有类都具有最后设置的值。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

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