如何在第一次调用函数时使数组初始化?

时间:2012-03-05 06:48:45

标签: ruby metaprogramming class-eval

class Class
  def attr_accessor_with_history(attr_name)
    attr_name = attr_name.to_s
    # make sure it's a string                                                                                                                          
    attr_reader attr_name
    # create the attribute's                                                                                                                           

    attr_reader attr_name+"_history" # create bar_history                                                                                              

    class_eval %Q{

      def #{attr_name}=(val)
        @#{attr_name+"_history"}=[]
        @#{attr_name+"_history"}.push(val)
        @#{attr_name}=val
      end
    }
  end
end

class Foo

  attr_accessor_with_history :bar
end

我想创建attr访问器,它会记录数组中所有写入的历史记录,但问题是在class_eval中每次都初始化数组,因此它不会保留旧值。

我应该做些什么改变?

1 个答案:

答案 0 :(得分:3)

使用||=

@#{attr_name+"_history"} ||= []