DEV Community

Cover image for Refinements in ruby
Adam Piotrowski for 2n IT

Posted on

3 3

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
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more