In this article, we’re going to explore the following topics:
If you’re familiar with the notion of environment in the Ruby on Rails framework then you probably had to deal with the
Rails.env.production? method in order to control an execution flow depending on the current environment
rails> Rails.env.production? => false
rails> Rails.env.development?=> true
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?
First, let’s have a look to what’s
Here we can see that the
Rails.env object is an instance of the class
This class inherits from
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
The method_missing hook method
production? method is called on an instance of the
ActiveSupport::StringInquirer class then the
ActiveSupport::StringInquirer#method_missing hook method is called as the
production? methods isn’t implemented in this class.
This hook method is invoked when the
ActiveSupport::StringInquirer method lookup path is traversed and none of the classes can handle the
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
2- if so, it compares
self with the message name without the
3- finally, the result of this comparison is returned.
respond_to? production? returns
true even though the
production? method isn’t defined on the
So how the magic works behind the scene?
The respond_to_missing? hook method
When you implement a strategy using the
method_missing hook method, then it’s difficult to know to which method the class that implement this hook method can respond.
production? method is not defined — as its behavior is delegated to the
So what happens if we execute this statement?
Here, we’d like that this statement returns
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
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