1
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 中,数组每次都被初始化,因此它不保存旧值。

我应该做些什么改变?

4

1 回答 1

3

使用||=

@#{attr_name+"_history"} ||= []
于 2012-03-05T07:04:07.993 回答