Hey, folks. Today we're going to talk about metaprogramming and look at one metaprogramming technique in detail.
Metaprogramming is a pretty scary sounding word, I think. It's even more scary sounding when people describe it to you as code that writes code. I don't know what that means, but the best way I have to describe metaprogramming is code that is dynamically evaluated so that you can modify the existing classes and functions that you have in your program.
I think that's more concrete to understand. I think an even better way of understanding it is to actually go ahead and take a look at one metaprogramming technique.
We're going to add to the object prototype a method called defineMethod. This is going to be code that alters our classes or objects in order to add methods to those objects.
It's configurable, meaning we can redefine it at any time if we like to. And then the value of this property is going to be the method body.
Let's see what this looks like in action. I'm going to define an object called dog. It's going to be of the breed Sheltie so now we have this object. Let's say dog.defineMethod and we'll give it...How about bark? And so, it'll be a function here. We'll just return woof.
And so, now we can say dog.bark -- very, very simple. This technique is called dynamic method. The reason it can be incredibly useful is because we can use it over and over again to define the same type of method in the exact same way.
Here I've got a user constructor, which is very like a class. We'll give the user a couple of statuses that it could be. I have a library called Lo-Dash here which we'll use to loop through each of the statuses. We'll say user.statuses. We'll get each of those statuses.
We'll say this.defineMethod. We'll define is+status.capitalize. I'm getting this capitalize functionality from another library called Active Support which I'll show you.
We'll need to make sure that we return this so that it returns true or false. We'll process this in the context of this.
Now we can say user=newuser. We can say user.status=active. Then we have these two methods here. If we look, we already can see that they're on our user objects. We can say user.isactive. That should be true. And user.isinactive. That should be false.
I hope this helps to reinforce that metaprogramming is no different from programming in general. We're defining some helper methods that help us to write the code that we wanted to write.
I promised that I'd show you these libraries. The first one was called Active Support. You can visit the GitHub link for that. It has methods like singularize, pluralize, and capitalize which we used.
And then Lo-Dash, which you can go to Lo-Dash.com/docs in order to read more about that -- these are some common libraries that I use in metaprogramming.