2

我有这个方法:

  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

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

我正在考虑这段代码:

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

1 回答 1

5

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

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

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

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
于 2016-02-16T08:02:54.807 回答