Incorporating respond_to_missing to conform to metaprogramming best practices

In the previous section, you learned about a metaprogramming method called method_missing.

As mentioned earlier, the problem with this method is that most developers tend to use the respond_to? method to check whether the method is present and, only if the value is true, the rest of the code is executed. To ensure that we're conforming to Ruby best practices, override the respond_to? method, like so:

def respond_to_missing?(method_name, include_private = false)
method_name.to_s.start_with?('author_') || super
end

In this code, we passed two arguments to the method and, in the next line, we created a conditional that is similar to the one in method_missing. However, we are using a different syntax to get more familiar with different syntaxes.

Instead of using an if...else statement, we simply execute the same functionality on a single line. This code first converts the method_name into a string and checks whether it starts with the word author_. If so, it returns the value true; otherwise, it returns false.

Though this syntax is much shorter, it won't work so well in the method_missing method. In that method, we send a value, whereas, here, we simply check for the presence of a certain word. So, even if we can technically write the code in a single line in method_missing, it might look confusing. I have no qualms writing three lines of code instead of one if it results in the code being more explicit and easier to understand.

When we run this code, the output is:

"Computer Science"
true

You can see the method has returned the value true, and this is in tune with the established programming practices.

You can now use this code as a template when you do metaprogramming in future.

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

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