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:

# Overriding method missing.

def method_missing(method, *args, &block)
  puts hello

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 method_missing.

Rails uses 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.

  class Object
    def self.const_missing(constant)
      # convert constant to snake_case from CamelCase
      # look through a directory structure for the snake_case version of the constant
      # e.g. UserMailer would be converted to user_mailer.rb

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.