Project

General

Profile

Actions

Feature #21435

open

Kernel#optional as a conditional #then

Added by Alexander.Senko (Alexander Senko) 4 days ago. Updated 2 days ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:122506]

Description

What

When chaining, I need sometimes to apply some changes conditionally, like this:

@record = Record.find(record_id)
  .then { it.respond_to?(:decorate) ? it.decorate : it }

It would be great to DRY it a bit:

@record = Record.find(record_id)
  .optional { it.decorate if it.respond_to? :decorate }

Or, even shorter for Rails users:

@record = Record.find(record_id)
  .optional { it.try :decorate }

Why

The intent is to make it visible at a glance that a statement may affect the result, but not necessarily does so. Without the proposed method, one needs to read and parse the whole block to know that.

It should help to read longer processing chains, for those who prefer chains and #then to plain old iterative approach.

Naming

It is discussible. I have just two ideas yet:

  • optional
  • maybe

Reference implementation

# Yields self to the block and returns the result of the block if it’s
# truthy, and self otherwise.
def optional
  tap do
    result = yield(self) or next

    break result
  end
end
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like1Like0Like0Like0Like0