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 に答える