Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What replace silence (capture) kernel method in Rails 5?

I use the silence method on my spec (http://apidock.com/rails/Kernel/capture).

For example, I want to avoid display on this block :

silence(:stdout) do
  ActiveRecord::Tasks::DatabaseTasks.purge_current
  ActiveRecord::Tasks::DatabaseTasks.load_schema_current
end

It work well but it's mark as deprecated since Rails 4. As it will be remove on next release, I search a replacement but didn't find.

Does something thread-safe exist? Does a replacement exist?

like image 251
Naremy Avatar asked Oct 26 '15 16:10

Naremy


1 Answers

Nothing replaced it. Noting that this is not thread-safe, here's what I now have in spec_helper.rb:

# Silence +STDOUT+ temporarily.
#
# &block:: Block of code to call while +STDOUT+ is disabled.
#
def spec_helper_silence_stdout( &block )
  spec_helper_silence_stream( $stdout, &block )
end

# Back-end to #spec_helper_silence_stdout; silences arbitrary streams.
#
# +stream+:: The output stream to silence, e.g. <tt>$stdout</tt>
# &block::   Block of code to call while output stream is disabled.
#
def spec_helper_silence_stream( stream, &block )
  begin
    old_stream = stream.dup
    stream.reopen( File::NULL )
    stream.sync = true

    yield

  ensure
    stream.reopen( old_stream )
    old_stream.close

  end
end

It is inelegant but effective.

like image 89
Andrew Hodgkinson Avatar answered Nov 07 '22 21:11

Andrew Hodgkinson