DEV Community

Michael Monerau
Michael Monerau

Posted on

Ruby - suppress those warnings you can't do anything about

Ever encountered a situation where you get warnings from code in gems you are requiring?

...
/home/qortex/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/amazing_print-1.0.0/lib/amazing_print/formatter.rb:29: warning: mismatched indentations at 'end' with 'else' at 27
...

It doesn't feel good, right? Depending on your toolchain and CI/CD pipelines, it can lead to annoying noise.

I started encountering some of those warnings when running RSpec with the warnings flag on (which is useful because it helps catching some smells in code).

Fix them?

In those cases, you do not own the codebase the warnings originate from. So you are out of luck because you can't fix them by yourself. You have to submit a PR, and/or wait for the maintainers to release a fix - if they ever do. It can take time.

Sometimes, the warnings are just expected and should be silenced.

Suppress them!

So now you think the warnings can be safely ignored, and you would like to suppress them.

A gem does exactly that, it's called warnings and has been made by the well-known and amazing rubyist Jeremy Evans.

Just put gem 'warning' in your Gemfile, and silence warnings from all your required gems with a simple snippet:

require 'warning'
Gem.path.each do |path|
  Warning.ignore(//, path)
end

In a RSpec context, you typically put that at the top of your spec_helper.rb file.

In any other context, just put that before requiring the gems that output warnings.

You can also be more precise in the warnings you'd like to ignore, by targeting them specifically. For example, to silence the exact warning shown above:

# first param is a regexp matching the message
# second param is a regexp matching the file path
Warning.ignore(/.*mismatched indentations.*/, /.*amazing_print.*/)

Latest comments (0)