After too long of a break, I’m getting back into Rebuilding Rails. In chapter 3, Noah explains how Rails uses automatic loading to make our lives as developers easier.If you’ve ever worked with Rails before, you know that you can refer to a class, like a controller, from almost anywhere in Rails, and didn’t have to
require the new controller file anywhere. How does this work?
Something is missing
When the Ruby interpreter comes across a keyword in your program, but it can’t find a method or variable defined for that keyword, it calls the
method_missing method. This method will throw an error explaining that Ruby couldn’t find any variable or method with that name. Like most built-in Ruby methods,
method_missing can be overridden. For example:
Here you can see that
method_missing gives you access to the method that was called, any number of arguments, and the block that is passed to it. From here, you can execute any code, like dynamically defining the method that was missing.
But what about when you reference a class that Ruby doesn’t know about, like a controller? Since classes are just constants, you can use
const_missing, which has similar behaviour to
const_missing to search through the file structure of the project to search for any constant that is referred to, but not explicitly included in the file.
So, if you called
UserMailer.welcome_email.deliver, you don’t have to put a
require at the top of your file. Ruby will look up that constant for you.
This seems like really little stuff, but it’s cool seeing how Ruby and Rails make things convenient for developers.