Ruby refinements example

Refinements is a Ruby 2.0 answer to monkey patches that can take control of your program without you realizing it. Next time you will be tempted to monkey patch something, think twice and consider using refinements.

Let’s say we want to use the ordinal method from ActiveSupport without requiring AS and without monkey-patching directly.

Here is how a refinement of that would look like:

Now if I want to use this within my application I can just tell Ruby I want to use the refined classes with using keyword:

This would change the string behaviour for the whole file. Since Ruby 2.3 we can use it explicitly within a class:

Leave a comment

Your email address will not be published. Required fields are marked *