在代码块上使用guard子句

时间:2016-02-16 07:47:20

标签: ruby rubocop

我有这个方法:

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

1 个答案:

答案 0 :(得分:5)

  

我正在使用rubocop错误来使用一个保护条款而不是一个   if-else声明...... 最好的方法是什么

首先仔细阅读一些关于保护条款的文章。

以下是重构使用guard子句的方法:

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
相关问题