Ruby: How To Avoid A respond_to? Call
I’m writing this post as contribution to the Campagna Anti-IF (Anti-IF Campaign).
Problem
I’m developing an internal Rails plugin for widgets, it provides a class called Widget (really unconventional :-P), and each widget should inherit from it.
The actual implementation provides a callback called before_render, that allows to add some logic to a widget, if implemented it’s called before the widget rendering.
Ruby doesn’t have abstract methods, so I have to check if the subclass has the implementation of mentioned method:
# Rendering code..
before_render if respond_to? :before_render
# ...
As you can see it’s an inefficient and inelegant way to render the widget, cause we always check if the method was implemented, and because I have introduced an if statement.
Solution
I added to Widget an empty before_render method: if the method it wasn’t implemented into the subclass the rendering code will be safely called.
Here the new code:
def before_render
end
# Rendering code..
before_render
# ...