Question

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

i want to make attr accessor which would record the history of all writes in an array but the problem is in the class_eval the array is initialized every time so it doesnt hold the old values.

what changes should i do?

Was it helpful?

Solution

Use ||=:

@#{attr_name+"_history"} ||= []
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top