I just discovered Ruby’s metaprogramming (after 7 years of using Ruby, it was about time!) and I have this question:
Assuming I run a program that uses class_eval and other metaporgramming functions to add methods to a class, is there an easy way, when re-running the same program, to have these new methods already defined, or do I have to program my own system which, every time class_eval is used, also save the generated code in a file in order to re-evaluate it the next time I run the program?
Thanks
This is not how it’s done. A proper way is, when you run the program next time, to run all those calls to
define_method,class_eval(and whatnot) again and define methods in run-time.Imagine what would happen if generated methods persisted in your source code? Would you like your
attr_accessorto replace itself with two new methods?What if you’re writing such a meta-method yourself and you change it. How do you think all those saved generated methods will be updated?
I don’t know where you read about metaprogramming, but I strongly recommend this book: Metaprogramming Ruby. It should clear your head. 🙂