How to suppress Rails console/irb outputs

后端 未结 6 992
一生所求
一生所求 2020-12-07 14:01

I\'m stuck with a pretty weird problem.

I was testing some db entries in our production server in Rails Console where almost all the commands were resulting a huge n

6条回答
  •  一个人的身影
    2020-12-07 14:32

    Supress Output, In General

    Also, depending on your needs, have a look at using quietly or silence_stream for suppressing output in general, not just in the irb/console:

    silence_stream(STDOUT) do
      users = User.all
    end
    

    NOTE: silence_stream removed in Rails 5+.

    NOTE: quietly will be deprecated in Ruby 2.2.0 and will eventually be removed. (Thanks BenMorganIO!)

    More information can be found here.

    Work Around for Rails 5+.

    As mentioned above, silence_stream is no longer available because it is not thread safe. There is no thread safe alternative. But if you still want to use silence_stream and are aware that it is not thread safe and are not using it in a multithreaded manner, you can manually add it back as an initializer.

    config/initializer/silence_stream.rb

    # Re-implementation of `silence_stream` that was removed in Rails 5 due to it not being threadsafe.
    # This is not threadsafe either so only use it in single threaded operations.
    # See https://api.rubyonrails.org/v4.2.5/classes/Kernel.html#method-i-silence_stream.
    #
    def silence_stream( stream )
      old_stream = stream.dup
      stream.reopen( File::NULL )
      stream.sync = true
      yield
    
    ensure
      stream.reopen( old_stream )
      old_stream.close
    end
    

提交回复
热议问题