【问题标题】:How do I add an if-condition to a Rails.logger.silence do-loop?如何向 Rails.logger.silence 循环添加 if 条件?
【发布时间】:2020-05-11 11:20:02
【问题描述】:

我想在特定条件下使特定控制器的日志静音。对于@product,有一个@product.sensitive(布尔值)属性。如果@product.sensitive == true,我希望#show-controller 不记录任何内容。这就是解决没有条件(对我来说很好)使所有日志静音的方法:

def show
  Rails.logger.silence do
    if @product.price > 0
      # Do this
    else
      # Do that
    end
  end
end

但是,如果我现在希望 Rails.lgger.silence 以 @product.sensitive == true 为条件呢?我做不到:

 def show
    if @product.sensitive
          Rails.logger.silence do
    end
            if @product.price > 0
              # Do this
            else
              # Do that
            end
          end
    if @product.sensitive
    end
    end
end

那么,哇,我要解决这个问题吗?我想有两种不同的解决方案:要么只有在@product.sensitive == true 的条件下激活循环,​​要么以任何其他方式简单地禁用记录器(并在控制器结束时重新激活它)。

我有什么选择?

【问题讨论】:

    标签: ruby-on-rails logging


    【解决方案1】:

    您可以将“真实”代码放入 lambda 中,并酌情在 Rails.logger.silence 内部/外部运行它:

    def show
      the_real_work = -> do
        if @product.price > 0
          # Do this
        else
          # Do that
        end
      end
      if @product.sensitive
        Rails.logger.silence(&the_real_work)
      end
        the_real_work[]
      end
    end
    

    或使用单独的方法:

    # This would probably be private in real life.
    def the_real_show
      if @product.price > 0
        # Do this
      else
        # Do that
      end
    end
    
    def show
      if @product.sensitive
        Rails.logger.silence { the_real_show }
        # or Rails.logger.silence(&method(:the_real_show))
      end
        the_real_show
      end
    end
    

    如果在调用 #show 之前在 before_action 中创建了(或可以)@product,您可以将事情从里到外:

    # Of somewhere private...
    def silence_logging
      Rails.logger.silence { yield }
    end
    
    def needs_silencing?
      action_name == 'show' && @product.sensitive
    end
    

    然后将静音连接起来。

    before_action :whatever_already_loads_the_product
    around_action :silence_logging, if: :needs_silencing?
    

    很遗憾,您不能混合使用:if:only 选项,因为:if 会覆盖:only,否则您可以说if: :sensitive_product, only: :show 之类的内容。

    【讨论】:

    • 我无法让 lambda 版本适用于静音版本,但单独的方法运行良好。谢谢!
    猜你喜欢
    • 2017-09-14
    • 2019-12-06
    • 1970-01-01
    • 2022-12-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多