gpt4 book ai didi

ruby - 在代码块上使用保护子句

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:55 24 4
gpt4 key购买 nike

我有这个方法:

  def self.get_image(product_id)
self.initialize

product_id=product_id.to_s
if @image_db.key?(product_id)
if Time.now.to_i - @image_db[product_id][':cached_at'] > @refresh_period
puts Time.now.to_i - @image_db[product_id][':cached_at']
self.cache_image(product_id)
else
return @image_db[product_id][':uri']
end
else
self.cache_image(product_id)
end
end

并且我遇到了使用保护子句而不是 if-else 语句的 rubocop 错误。最好的方法是什么?

我正在考虑这段代码:

  def self.get_image(product_id)
self.initialize

product_id=product_id.to_s
return if @image_db.key?(product_id)
return if Time.now.to_i - @image_db[product_id][':cached_at'] > @refresh_period
puts Time.now.to_i - @image_db[product_id][':cached_at']
self.cache_image(product_id)
end

但是这一行永远不会被调用:

return @image_db[product_id][':uri']

最佳答案

and I am getting rubocop errors to use a guard clause instead of an if-else statement... what would be the best way to do this?

首先仔细阅读几篇关于什么是保护条款的文章。

这是重构为使用保护子句的方法:

def self.get_image(product_id)
initialize

product_id = product_id.to_s

return cache_image(product_id) unless @image_db.key?(product_id)
return @image_db[product_id][':uri'] unless Time.now.to_i - @image_db[product_id][':cached_at'] > @refresh_period
puts Time.now.to_i - @image_db[product_id][':cached_at']
cache_image(product_id)
end

我可能会将方法的某些部分移出以稍微简化它:

def self.get_image(product_id)
initialize
product_id = product_id.to_s
return cache_image(product_id) unless @image_db.key?(product_id)
return @image_db[product_id][':uri'] unless cached_at_gttn_refresh_period?(product_id)
puts Time.now.to_i - @image_db[product_id][':cached_at']
cache_image(product_id)
end

private

def cached_at_gttn_refresh_period?(product_id)
Time.now.to_i - @image_db[product_id][':cached_at'] > @refresh_period
end

关于ruby - 在代码块上使用保护子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35426626/

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