What is metaprogramming in Ruby/Rails and give examples?
Answer
Metaprogramming is writing code that writes or modifies code at runtime. Ruby's dynamic nature makes it powerful for metaprogramming. Key techniques: define_method(:foo) { ... } — defines a method dynamically; method_missing — called for undefined methods, used to implement dynamic finders; send(:method_name) — calls any method by name including private; class_eval / module_eval — opens a class to add methods at runtime; attr_accessor is itself a macro that calls define_method. Rails uses metaprogramming extensively — ActiveRecord's associations (has_many), validations (validates), and callbacks are all macros implemented via metaprogramming.
Previous
What is ActiveRecord dirty tracking?
Next
What is the difference between include, extend, and prepend in Ruby?
More Ruby on Rails Questions
View all →- Advanced What is the difference between include, extend, and prepend in Ruby?
- Advanced How does Rails handle database connection pooling?
- Advanced What is Rack and how does Rails relate to it?
- Advanced What is query optimization with explain in Rails?
- Advanced What are Rails engines and how are they used?