gpt4 book ai didi

ruby-on-rails - 如何优雅地处理 NilClass

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:10 25 4
gpt4 key购买 nike

我试图避免由于 NilClass 而导致的 NoMethod 错误。我的代码如下所示:

@branded, @nonbranded, @unknown, @affiliate, @social, @referral, @paid, @direct, @email = [], [], [], [], [], [], [], [], []

count = 0
while count < 6
date = SDLW + count
#TODO There has to be a better way than this.
branded_check = Metric.first(start_date: date, end_date: date, source: 'branded')
nonbranded_check = Metric.first(start_date: date, end_date: date, source: 'nonbranded')
unknown_check = Metric.first(start_date: date, end_date: date, source: 'unknown')
affiliate_check = Metric.first(start_date: date, end_date: date, source: 'affiliate')
social_check = Metric.first(start_date: date, end_date: date, source: 'social')
referral_check = Metric.first(start_date: date, end_date: date, source: 'referral')
paid_check = Metric.first(start_date: date, end_date: date, source: 'paid')
direct_check = Metric.first(start_date: date, end_date: date, source: 'direct')
email_check = Metric.first(start_date: date, end_date: date, source: 'email')

branded_check = branded_check.nil? ? 0 : branded_check.visits
nonbranded_check = nonbranded_check.nil? ? 0 : nonbranded_check.visits
unknown_check = unknown_check.nil? ? 0 : unknown_check.visits
affiliate_check = affiliate_check.nil? ? 0 : affiliate_check.visits
social_check = social_check.nil? ? 0 : social_check.visits
referral_check = referral_check.nil? ? 0 : referral_check.visits
paid_check = paid_check.nil? ? 0 : paid_check.visits
direct_check = direct_check.nil? ? 0 : direct_check.visits
email_check = email_check.nil? ? 0 : email_check.visits

@branded << branded_check
@nonbranded << nonbranded_check
@unknown << unknown_check
@affiliate << affiliate_check
@social << social_check
@referral << referral_check
@paid << paid_check
@direct << direct_check
@email << email_check

count += 1
end

我确信必须有一种更简洁、更简洁的方法来做到这一点。尽管在谷歌上搜索和阅读,我还是没能弄明白。任何关于如何重构的想法都将不胜感激。

最佳答案

当然,创建一个避免重复自己的方法

def visits(tag, date)
check = Metric.first(start_date: date, end_date: date, source: tag)
check.present? ? check.visits : 0 # or 'check.nil? ? 0 : check.visits' if you prefer
end

在你的方法中

count = 0
while count < 6
date = SDLW + count

@branded << visits('branded', date)
@nonbranded << visits('nonbranded', date)
...

count += 1
end

关于ruby-on-rails - 如何优雅地处理 NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011121/

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