Ruby ecosystem allows us to modify or redefine existing class definitions. This is known as Monkey patching. These changes are scoped globally and once loaded, any piece of code can use the monkey patched class.
Refinements is a way to limit the scope of a monkey patched class. Using refinements, we can redefine an existing class locally.
In this example, we created Example class with no methods defined.
Later, it is redefined using Module#refine method to add Example#print_something method.
Refinement can be activated using using [Module Name]. Similar to Module#module_eval, Module#refine creates an anonymous module which keeps the changes or refinements to an existing class, Example class in this case.
Refinements can be activated at top level, class level or module level. It can not be activated at a method level.
Example refinements scope
Ruby method look up works as follows:
- If refinements are activated for Class, in the reverse order of they were activated.
– Prepended modules from the refinement for Class.
– Refinement for Class.
– Included modules from the refinement for Class.
- Prepended modules for Class.
- Class definition.
- The Included modules for Class.
Further reading on refinements
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management