What is Metaprogramming?

Have you ever wondered how Rails generates methods based on the models you’ve defined? This is done using Metaprogramming.

Image for post

What a gem.

Metaprogramming is writing programs that write programs. For example, when a User model is defined in Rails with email as an attribute, a method called find_by_email will be generated.

You never have to create the find_by_email method. Instead behind the scenes Rails is generating a bunch of great methods on the fly for you as a developer to use.

We can use this built in feature of Ruby to generate methods at runtime or on the fly.

I have created a repo to demonstrate. https://github.com/arichards4814/metaprogramming_article

The send Method

Before diving into metaprogramming, it is first important to take a look at the send method.

Image for post

In this situation, I want to insert this book info into a new instance of book. Without using the send method we can do this like so.

Image for post

This will print the book with its new attributes.

But we can do this much easier (and with less code) by creating a method within the Book class that can take care of this for us.

Image for post

This will produce the same result. Imagine if there were 10 or 20 values and how much time this would save.

So exactly what is going on here with the send method?

self.send("#{k}=", values[k])

As the we loop through each key value pair in book_info, we use “message passing” to “send” a method to “self”.

So in other words, we are the first argument in send as the method name we want to pass. And the second as the argument to that method.

#metaprogramming #rubygems #ruby-on-rails-development #ruby #ruby-on-rails

Metaprogramming in Ruby
2.05 GEEK