How environment check works in Ruby on Rails? - Mehdi Farsi

By Mehdi Farsi

Have you seen my cat?

In this article, we’re going to explore the following topics:

  • the Rails.env object
  • the respond_to_missing? hook method

Rails.env.*?

rails> Rails.env.production? => false

rails> Rails.env.development?

=> true

rails> Rails.env.test?


=> false

In the above example, we can see that Ruby on Rails provides a method per environment.

But what if I tell you that these methods don’t really exist?

ActiveSupport::StringInquirer

Here we can see that the Rails.env object is an instance of the class ActiveSupport::StringInquirer.

This class inherits from String.

So the Rails.env object is a string that represents the current environment.

Now that we’re more familiar with the Rails.env attribute, then let’s have a look to what happens behind the scene when I call the production? method on an instance of the ActiveSupport::StringInquirer.

The method_missing hook method

This hook method is invoked when the ActiveSupport::StringInquirer method lookup path is traversed and none of the classes can handle the production? message.

Feel free to have a look to this article if you’re not familiar with the notion method_missing hook method.

This hook method behaves as followed:

1- it checks if the unhandled message contains a ? suffix.

2- if so, it compares self with the message name without the ? suffix.

3- finally, the result of this comparison is returned.

The respond_to? production? returns true even though the production? method isn’t defined on the ActiveSupport::StringInquirer class.

So how the magic works behind the scene?

The respond_to_missing? hook method

Indeed, our production? method is not defined — as its behavior is delegated to the method_missing.

So what happens if we execute this statement?

Here, we’d like that this statement returns true.

That’s where the respond_to_missing? method comes into play

Here, we define a respond_to_missing? hook method that is implicitly called when we invoke respond_to? on an instance of the ActiveSupport::StringInquirer class.

This method returns a boolean that is true if the last character of the method_name argument is a ? or it calls super otherwise — which returns false by default.

So, in our case, Rails.env.respond_to :production? returns true because it matches the condition in the respond_to_missing? method.

Voilà!

ONE MORE THING ⬇