防止未定义的链式方法
我有一个很长的循环,结果是这样的:
csv_code = CSV.generate do |csv|
csv << ["Product ID","Name", "Url"]
@all_products.each do |product|
if product.page_url("en_US") != nil
turl = product.page_url("en_US")
end
csv << [product.name,product.d_id, turl]
end
end
该方法使用产品 1-17 效果很好,导致打印出 url。当我到达第 18 条记录时,我遇到了问题
Product.find(18) // product found!
product.find(18).page_url("en_US")
NoMethodError: undefined method `page_url' for nil:NilClass
如何防范这些未定义事件?
url = 产品.page_url("en_US")
I have a long loop that results in this:
csv_code = CSV.generate do |csv|
csv << ["Product ID","Name", "Url"]
@all_products.each do |product|
if product.page_url("en_US") != nil
turl = product.page_url("en_US")
end
csv << [product.name,product.d_id, turl]
end
end
The method uses products 1-17 works great resulting in a url printed. When I get to my 18th record I have problems
Product.find(18) // product found!
product.find(18).page_url("en_US")
NoMethodError: undefined method `page_url' for nil:NilClass
How can I protect against these undefined events?
url = product.page_url("en_US")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是
product
为nil
:它与
page_url
可能返回nil 没有任何关系 code>。)
确保
product
不能为nil
:但要小心,这可能是一个更深层次的问题。无论如何,“修复”这个问题很容易。 。考虑使用集合 限制(例如 Enumerable#reject):
上面使用Symbol#to_proc“Rails 魔法”,但可以与限制一样,
{|x| x.nil?}
的缺点是,尽管Enumerable#partition 可以帮助解决这个问题:使用正确的工具来完成这项工作。另一个解决方案是扩大条件检查本身:
&&
的短路性质将确保page_url
仅在真值时调用(不包括nil
)。我还冒昧地假设
page_url
无法返回false
,因为我发现这使得意图更加清晰。快乐编码。
The issue is that a
product
isnil
:(It has nothing to do with
page_url
maybe returningnil
.)Make sure
product
can't benil
: but be wary that this may be a deeper issue. In any case, "fixing" this issue is easy to deal with.Consider either using a collection restriction (such as Enumerable#reject):
The above uses the Symbol#to_proc "Rails magic", but could just as easily have been
{|x| x.nil?}
as the restriction. The downside is it's not practical to use this for a "no URL" condition per-product although Enumerable#partition could help with that: use the right tool for the job.Another solution is to expand the conditional check itself:
The short-circuit nature of
&&
will ensurepage_url
is only invoked upon a truthy value (which excludesnil
).I also took the liberty of assuming
page_url
can't returnfalse
as I find this makes the intent more clear.Happy coding.
试试这个:
但它是性能杀手。
您确定
Product.find(18)
不会返回nil
吗?无论如何,你可以这样做:
Try this:
But it's a perf killer.
Are you sure
Product.find(18)
doesn't returnnil
?Anyway, you could do: