Metaprogramming introduction

We will start learning about metaprogramming in Ruby. Let's begin with a practical example. Refer to the following screenshot:

This is a profile page for devcamp.com. You can see my full name listed on the top right-hand side. This name was collected by the application when I signed up, and when I logged in later, it was retrieved from the database and displayed.

To display this value, you can update your User class in the application and override the built-in to_s string method, like so:

def to_s
self.first_name + " " + self.last_name
end

Now if you call the to_s method on any objects created from the User class, you'll get the full name value.

So metaprogramming gives us the ability to open up classes and override existing methods to assign custom behavior to applications. This is by no means the full scope of what metaprogramming offers, but it's an introduction to how you can easily use it in your applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.152.87