Utilizing metaprogramming with method_missing to create methods on the fly
This will be an interesting section. You are going to learn how to create code that will write code inside a Ruby program by leveraging the metaprogramming construct of method_missing
. Though it's an advanced Ruby concept, it's fun to learn and I think it'll be handy for you. So let's get started.
Imagine we have a database called Author
, and, in it, we have different attributes, such as first_name
, last_name
, and genre
. What do we do if we want to create dynamic methods on the fly? For example, if we create a new author in the database, we want custom methods to print out each of the attributes. At the same time, we don't want to hardcode a bunch of methods; we want them to get generated dynamically. Essentially, we want a metaprogramming method that will write code dynamically on the fly based on the arguments sent to it.
Let's see how to do that:
require 'ostruct' class Author attr_accessor :first_name, :last_name...