Feature idea: implementing `Object#presence!`

I’d like to suggest adding Object#presence! to ActiveSupport core extensions to give the option to easily accept only a value which is present? and otherwise raise an exception, much like Enumerable#sole either returns the sole value or raises.

This would typically help ensuring ensuring that a method doesn’t return a nil value in this fashion:

def compute_value
  # ...

  value.presence!
end

I’ve seen that changes to ActiveSupport core extensions are heavily discouraged but since there seem to be no plans to port Object#present? or Object#blank? to ruby, and that Object#presence will most likely keep being supported, I thought it was worth bringing up still.

3 Likes

Personally, I’m on the fence. While it seems convenient, I would prefer being explicit about the error type: value.presence or raise ValueNotFound.

I also wonder if the naming fits other ActiveSupport core extensions. Outside of try!, we don’t see many bang methods monkey-patched onto Object that don’t mutate self.

Also, it could lead to some API bloat, where every predicate method eventually demands a corresponding bang (!) version: many!, none!, etc.

1 Like