I'm doing the SaaS Stanford class, trying to do Part 5 of this assignment
I'm having a really hard time grasping this concept, this is what I've attempted to do:
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'{def #{attr_name}(a);#{attr_name}_history.push(a) ; end;}'
end
end
I'm probably doing all sorts of things wrong, read The Book Of Ruby chapter on metaprogramming and I still don't get it, can someone help me comprehend this?
This was fun!!!
Note that the only reason you need to use strings with class_eval is so that you can refer to the value of
attr_name
when defining the custom setter. Otherwise one would normally pass a block toclass_eval
.With regard to what you've done you're actually on the cusp of the solution. It's just that
#{attr_name}_history
doesn't exist in your code. You will need to create an instance variable and set it to nil if it doesn't exist. What you have already should handle pushing into the array if it does exist.There are several ways to do that. One way is
if defined? @#{attr_name}_history DoStuffHere
You must notice that
#{attr_name}_history
is a instance variable, so use @ before, like @foo in the class belowdef #{attr_name}=value
,#{attr_name}=
is the method name,value
is parameter, same asdef func parameter