在代码块上使用保护子句



我有这个方法:

  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']

我收到使用保护子句而不是 如果-否则声明...最好的方法是什么

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

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

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

最新更新