I am using class_eval
to write code to be executed under the context of current class. In the following code, I want to add a counter for changes of attribute value
it is not about class_eval
it is about @count
. if you define this variable at class level it will be a class instance variable
not an instance variable
.
class Class
def attr_count(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name # create the attribute's getter
class_eval %Q{
def #{attr_name}= (attr_name)
@attr_name = attr_name
if @count
@count += 1
else
@count = 1
end
end
def #{attr_name}
@attr_name
end
}
end
end
class Foo
attr_count :bar
end
f = Foo.new
f.bar = 1