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

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up