MΓ³dulo 27 Β· Metaprogramming & Rails Magic β LecciΓ³n 3 de 6 Β· ~8 min
define_method
Write methods from data β no repetition
define_method creates a method at runtime from a name and a block. Instead of hand-writing five nearly-identical predicates, you generate them from a list. This is the other half of metaprogramming: send calls methods dynamically, define_method defines them dynamically.
In an interview, say: "
define_methodgenerates methods from data at load time, so a list of statuses becomes a set of predicate methods with no duplication. It's exactly how ActiveRecord'senumgives youconfirmed?andcancelled?for free."