TECH

Refinements in ruby

Refinements in ruby

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

##How I Contributed to an Open Source Project Without Knowing the Framework I'm a Ruby on Rails developer with several years of experience across various projects and technologies. Two weeks ago,...

bloglist_item
Tech

You finally click Deploy. The terminal scrolls, CI is all green, and for a few seconds, you feel unstoppable. You open the app in production, click around, and everything seems fine. Then an...

bloglist_item
Tech

The buzzwords are Readability, Reusability, Maintainability. Here's the long version: Modern web applications can grow in complexity. We often need to manage workflows more complex than simple...

ul. Powstańców Warszawy 5
15-129 Białystok
+48 668 842 999
CONTACT US