I'm trying to track every class variable's history by metaprogramming. I'm not a fan of asking such questions but It took me 5 hours to be able to write these and from now on I have no idea how to proceed (I'm new to ruby, and this is the first time I'm playing with metaprogramming).
In my understanding; when attr_accessor_with_history initializes in a class, it should execute the code it is containing. Thus, every time this method initializes, by the merits of metaprogramming every class is going to have its own method for the problem I described.
In the code I submitted, readers are initialized properly but I can't say the same about the code in class_eval part. I need clarification about why the code isn't working, and metaprogramming in general.
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
attr_reader attr_name + "_history"
class_eval "%Q{
@#{attr_name}_history=[nil]
def #{attr_name}=(value)
#{attr_name}=value
#{attr_name}_history.push(value)
end
}
"
end
end
class Klass
attr_accessor_with_history :kamil
def initialize(value)
kamil = value
end
end
a = Klass.new(5)
a.kamil = 1
puts "#{a.kamil_history}"
%Qin quotes for theclass_evalbit.%Q{...}evaluates to an interpolated string.