DEV Community

Augusts Bautra
Augusts Bautra

Posted on

1

A small refactor story

I was working on AREL expression chaining and stumbled on an opportunity to use reduce/inject.

This is easy to understand, but verbose, and suffers from treating the first value in a special way:

combo = expression_proc.call(values.first)

values[1..].each { combo = combo.and(expression_proc.call(_1)) }

combo
Enter fullscreen mode Exit fullscreen mode

This starts using reduce, but trades clarity for terseness, a downgrade:

combo = expression_proc.call(values.first)

values[1..].reduce(combo) do |mem, clause|
  mem.and(expression_proc.call(clause))
end
Enter fullscreen mode Exit fullscreen mode

Let's transform all values to expression objects to start.
reduce really could be aliased to chain_with. :)

clean_value.map { expression_proc.call(_1) }.reduce(:and)
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay