This blog is part of our Rails 5.1 series.
When we use method_missing
then we should also use
respond_to_missing?.
Because of this code becomes verbose since both method_missing
and
respond_to_missing?
need to move in tandem.
DHH in the issue itself provided a good example of this verbosity.
He proposed to use a new method
delegate_missing_to
. Here is how it
can be used.
Why not SimpleDelegator
We at BigBinary have used SimpleDelegator. However one issue with this is that statically we do not know to what object the calls are getting delegated to since at run time the delegator could be anything.
DHH had following to say about this pattern.
I prefer not having to hijack the inheritance tree for such a simple feature.
Why not delegate method
Delegate method works. However here we need to white list all the methods and in some cases the list can get really long. Following is a real example from a real project.
Delegate everything
Sometimes we just want to delegate all missing methods.
In such cases method delegate_missing_to
does the job neatly.
Note that the delegation happens to only public
methods of the object being delegated to.
Check out the pull request for more details on this.