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.

Refinement example

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_evalModule#refine creates an anonymous module which keeps the changes or refinements to an existing class, Example class in this case.

Scope

Refinements can be activated at top level, class level or module level. It can not be activated at a method level.

Example refinements scope

Lookup

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

http://ruby-doc.org/core-2.1.1/doc/syntax/refinements_rdoc.html

Click here for more details…


At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.

We also specialize in RPA, AI, Python, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!