Avoid these traps when nesting Ruby modules

But buried within Ruby's nesting implementation - and Rails' autoload system - are a few traps that can cause your code to fail in strange and wonderful ways. In this post, we'll discuss the origin of these traps and how you can avoid them.

Modules (and classes) are meant to be nested.  Code fragments like ActiveRecord::RecordNotFound are so common that we don't think twice about them. But buried within Ruby's nesting implementation - and Rails' autoload system - are a few traps that can cause your code to fail in strange and wonderful ways. In this post, we'll discuss the origin of these traps and how you can avoid them.

What is a constant?

This post is about modules, but to understand those we need to understand constants. In most languages, constants are only used to store little bits of data, like in the example below:

# These are simple constants
MAX_RETRIES = 5
DEFAULT_LANGUAGE = "en"

But in Ruby, classes and modules are also constants. I've written a little example to demonstrate this. There are three constants in the module below: a number, a class and a nested module. When you access a nested class or module, ruby finds it by using the same rules it would use with a simple numeric constant.

module MyModule
  MY_FAVORITE_NUMBER = 7

  # Classes are constants
  class MyClass
  end

  # So are modules
  module MyEmbeddedModule
  end
end

puts MyModule.constants.inspect # => [:MY_FAVORITE_NUMBER, :MyClass, :MyEmbeddedModule]

Often, modules have access to the constants defined in their parents. That's why you can write code like this:

module X
  MARCO = "polo"
  module Y
    def self.n 
      puts MARCO
    end
  end
end

X::Y.n() # => "polo"

But you'd be wrong if you thought that this parent/child relationship was what allows Y to access X's constant MARCO.

A common problem

If we rewrite the code above in a slightly different way, something surprising happens. Y can no longer access X::MARCO. What the heck is going on here?

module A
  MARCO = "polo"
end

module A::B
  def self.n 
    puts MARCO  # => uninitialized constant A::B::MARCO (NameError)
  end
end

A::B.n()

It turns out that the "inheritance" of a parent's constants by the child isn't due to the parent/child relationship. It's lexical. That means that it's based on the structure of your code, not on the structure of the objects your code is building.

Inspecting nesting

If you'd like to get a deeper understanding of how Ruby searches for nested constants, it's worth checking out the Module.nesting function.

This function returns an array of objects that make up the "search path" for constants in a given scope. Let's examine the nesting for our previous examples.

In our first example, we see that the nesting is [A::B, A]. This means that if we use the constant MARCO, Ruby will look for it first in A::B, and then in A.

module A
  MARCO = "polo"
  module B
    def self.n 
      puts Module.nesting.inspect  # => [A::B, A]
      puts MARCO # => "polo"
    end
  end
end

In the second example, we see that the nesting only includes A::B, not A. Even though B is a "child" of A, the way I've written the code doesn't show them as nested, so for this purpose they might as well not be.

module A
  MARCO = "polo"
end

module A::B
  def self.n 
    puts Module.nesting.inspect  # => [A::B]
    puts MARCO # => uninitialized constant A::B::MARCO (NameError)
  end
end

Rails autoload complications

Have you ever noticed that you don't have to include files when you use Rails? If you want to use a model, you just use it.

This is possible because Rails implements an autoload system. It uses Module.const_missing to detect when you try to reference a constant that hasn't been loaded. It then loads the files it believes should contain the constant. This works most of the time, but there's a catch.

Rails assumes that a module always has the largest possible nesting. It assumes that module A::B::C will have a nesting of [A::B::C, A::B, A]. If it doesn't you'll get unexpected behavior.

In the code below, module B shouldn't be able to access A::MARCO. In normal Ruby, it wouldn't be able to because its nesting is [A::B]. So you should get an exception. But Rails' autoload doesn't throw an exception. Instead, it returns A::MARCO.

# a.rb
module A
  MARCO = "polo"
end

# a/b.rb
module A::B
  def self.n 
    puts MARCO # => "polo"
  end
end

# some_controller.rb
A::B.n()

Conclusion?

All of this is a lot to think about. I prefer to avoid thinking where possible, so I try to stay away from the module A::B syntax. I can't think of a case where I would intentionally want to manipulate the module nesting. If you know of any, I'd love to hear about them!

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial