TECH

Refinements in ruby

blogpost

Today I had the opportunity to use https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html for the first time in my almost 8 years of Ruby programming.
So in general it works in the way that you can override some classes in Ruby but the change is not globally.
It creates the module, applies monkey patching, and using ModuleName. That makes things overridden only in the context of
the runtime of that using.

Let's describe it with my use case example. In application, we had an evaluator for formulas. Implementation details are not important, what we should focus on is that after parsing data we had a simple eval like that:
max( nil * 10, 20 )

Normally any operation like * on a nil object raises an error and that was ok. But in this case, we have a proper value of 20 which should be the result of that code since it is the maximum value from passed values.

So my solution is to expand basic arithmetic methods in NilClass, and thanks to using refinement i did it only in the context of our evaluator without causing any changes in the rest of application.

  class Evaluator
    Refinement = Module.new do
      refine NilClass do
        %i[- + / *].each do |operator|
          define_method(operator) { |_| nil }
        end
      end
    end

    using Refinement

    def initialize
      (...)
     end
  end

Read more on our blog

Check out the knowledge base collected and distilled by experienced
professionals.
bloglist_item
Tech

Over the years I had to deal with applications and system that have a long history of already being "legacy".
On top of that I met with clients/product owners that never want you to spend time ref...

bloglist_item
Tech

How many times have you searched for that one specific library that meets your needs? How much time have you spent customizing it to fit your project's requirements? I must admit, waaay too much. T...

Powstańców Warszawy 5
15-129 Białystok

+48 668 842 999
CONTACT US