Incorporating respond_to_missing to Conform to Metaprogramming Best Practices
In this guide we're going to learn how to implement the necessary code for getting the Ruby respond_to? method to pass for any dynamically created methods in a program that contains metaprogramming mechanisms.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In the previous lesson, we learned about a metaprogramming method called method_missing.

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

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

In this code, we are passing two arguments to the method, and in the next line, we are creating 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 are simply executing the same functionality on a single line. This code first converts the method_name into a string and checks if 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 method_missing method because in that method, we are sending a value whereas here, we are simply checking 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. And I have no qualms writing 3 lines of code instead of 1 if it results in the code being more explicit and easier to understand.

When we run this code, the output is:

"Computer Science"
true

Now, if you see the method has returned the value true, and this is in tune with established programming practices.

You can now use this code as a template when you do meta-programming in the future.

Resources