gpt4 book ai didi

ruby - Ruby 中优雅的日期解析

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:38 25 4
gpt4 key购买 nike

我在 Controller 操作中有两个日期参数,如果它们为零或解析失败,我想回退到默认值。

不幸的是,如果解析失败,DateTime.strptime 似乎会抛出异常,这迫使我写下这个怪物:

starting = if params[:starting].present?
begin
DateTime.strptime(params[:starting], "%Y-%m-%d")
rescue
@meeting_range.first
end
else
@meeting_range.first
end

感觉不好的人。有没有什么方法可以使用不需要 begin...rescue block 的 Ruby stdlib 来解析日期? Chronic对于这种情况感觉有点矫枉过正。

最佳答案

一般来说,我不同意其他解决方案,以这种方式使用 rescue 是不好的做法。我认为值得一提,以防其他人尝试将该概念应用于不同的实现。

我担心的是,您可能感兴趣的其他一些异常会被该rescue 隐藏,从而违反早期错误检测 规则。

以下是针对 Date 而不是 DateTime 但您会明白的:

Date.parse(home.build_time) # where build_time does not exist or home is nil
Date.parse(calculated_time) # with any exception in calculated_time

不得不面对同样的问题,我最终按如下方式对 Ruby 进行了猴子修补:

# date.rb
class Date
def self.safe_parse(value, default = nil)
Date.parse(value.to_s)
rescue ArgumentError
default
end
end

值中的任何异常都会在进入该方法之前上升,并且只会捕获 ArgumentError(尽管我不知道任何其他可能的异常)。

内联 rescue 的唯一正确用法与此类似:

f(x) rescue handle($!)

更新

这些天我更喜欢猴子补丁Ruby。相反,我将我的 Date 包装在 Rich 模块中,我将其放入 lib/rich 中,然后用以下代码调用它:

Rich::Date.safe_parse(date)

关于ruby - Ruby 中优雅的日期解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5782699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com