module Kernel
def capture(stream)
stream # => "Cool\n"
stream = capture(:stdout) { puts "Cool" }
Captures the given stream and returns it:
def capture(stream) begin stream = stream.to_s eval "$#{stream} = StringIO.new" yield result = eval("$#{stream}").string ensure eval("$#{stream} = #{stream.upcase}") end result end
def class_eval(*args, &block)
def class_eval(*args, &block) singleton_class.class_eval(*args, &block) end
def debugger
def debugger message = "\n***** Debugger requested, but was not available (ensure ruby-debug is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n" defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message) end
def enable_warnings
def enable_warnings with_warnings(true) { yield } end
def quietly
quietly { system 'bundle install' }
Silences both STDOUT and STDERR, even for subprocesses.
def quietly silence_stream(STDOUT) do silence_stream(STDERR) do yield end end end
def silence_stderr #:nodoc:
For compatibility
def silence_stderr #:nodoc: silence_stream(STDERR) { yield } end
def silence_stream(stream)
end
puts 'This will never be seen'
silence_stream(STDOUT) do
Silences any stream for the duration of the block.
def silence_stream(stream) old_stream = stream.dup stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') stream.sync = true yield ensure stream.reopen(old_stream) end
def silence_warnings
end
value = noisy_call # no warning voiced
silence_warnings do
Sets $VERBOSE to nil for the duration of the block and back to its original value afterwards.
def silence_warnings with_warnings(nil) { yield } end
def singleton_class
def singleton_class class << self self end end unless respond_to?(:singleton_class) # exists in 1.9.2
def suppress(*exception_classes)
end
puts "This code is NOT reached"
1/0
suppress(ZeroDivisionError) do
Blocks and ignores any exception passed as argument if raised within the block.
def suppress(*exception_classes) begin yield rescue Exception => e raise unless exception_classes.any? { |cls| e.kind_of?(cls) } end end
def with_warnings(flag)
def with_warnings(flag) old_verbose, $VERBOSE = $VERBOSE, flag yield ensure $VERBOSE = old_verbose end