Project

General

Profile

Feature #14672

Introduce a Date.safe_parse method

Added by coorasse (Alessandro Rodi) 3 months ago. Updated 3 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:86488]

Description

This feature request is about a Date.safe_parse method.
The method should call the original Date.parse method but avoid raising an exception and returning a fallback value instead.
An implementation in ActiveSupport has been proposed here: https://github.com/rails/rails/pull/32503/files.
This would avoid the necessity to rescue possible Exceptions everytime.

See:

Date.safe_parse(nil) 
=> # nil

Date.safe_parse("") 
=> # nil

fallback = Date.new(2018,1,1)
Date.safe_parse(nil, fallback)
=> # #<Date: 2018-01-01>

History

#1 [ruby-core:86491] Updated by shevegen (Robert A. Heiler) 3 months ago

I can understand the proposal.

I think your primary use case is to be able to use less code,
without needing to rescue all (or the important) errors specifically
via begin/rescue.

Perhaps it can be mentioned in the ruby developer meeting to see how
matz feels about API and usage pattern. (Also in general, e. g. for
all future proposals that aim to reduce explicit begin/rescue
clauses; see also how 'pp' became usable by default, without being
required to use an explicit "require 'pp'" line anymore since a
while).

As method name I would think Date.failsafe_parse() may be good too :D

Alternatively, perhaps use a shorter name, but provide an additional
argument possibility, such as :exception or something like that, to
allow for the above behaviour.

#2 [ruby-core:86510] Updated by janfri (Jan Friedrich) 3 months ago

Why not just use a one line rescue?

Date.parse(some_value) rescue Date.new(2018,1,1)

It shows IMHO the intention very clear.

#3 [ruby-core:86514] Updated by ahorek (Pavel Rosický) 3 months ago

http://blog.honeybadger.io/benchmarking-exceptions-in-ruby-yep-theyre-slow

exceptions are used a lot in parsers
https://github.com/ruby/csv/blob/master/lib/csv.rb#L342
having an oportunity to skip exception handing could also improve performance

I prefer an argument version, btw. sockets already have simmilar logic since ruby 2.3

@socket.connect_nonblock(@addr, exception: false)

example

Date.parse(some_value, exception: false) || Date.new(2018,1,1)

#4 Updated by coorasse (Alessandro Rodi) 3 months ago

  • Subject changed from Introdice a Date.safe_parse method to Introduce a Date.safe_parse method

#5 [ruby-core:86577] Updated by coorasse (Alessandro Rodi) 3 months ago

As pointed out by ahorek (Pavel Rosický), is not really good to use, raise, catch exceptions in ruby because yes...they are slow.
A one line rescue is what I used in the past, but it feels hacky and is a catch-all rescue which is never a good approach.
In the end, rubocop now defines it as bad practice and corrects it automatically.
See also https://robots.thoughtbot.com/don-t-inline-rescue-in-ruby

Also available in: Atom PDF