DEV Community

Augusts Bautra
Augusts Bautra

Posted on

Resolving "rb_check_safe_obj will be removed in Ruby 3.0" warning

TL;DR Paste this in an initializer or very early in require chain.

# Problem on Ruby 2.7
# > BigDecimal(1).to_s("F")
# (pry):1: warning: rb_check_safe_obj will be removed in Ruby 3.0
# This monkeypatch silences it.
# TODO: remove when on Ruby 3+
module BigDecimalFormatWarningSuppressor
  # NOTE: this API comes from ActiveSupport::NumericWithFormat, the last ancestor prepended to
  # BigDecimal.
  def to_s(format = nil, options = nil)
    original_verbosity = $VERBOSE
    $VERBOSE = nil
    v = super
    $VERBOSE = original_verbosity
    v
  end
end

BigDecimal.prepend(BigDecimalFormatWarningSuppressor)
Enter fullscreen mode Exit fullscreen mode

Discussion

Not sure what the deal is with BigDecimal's string formatting, but we can see in #to_s's source that it does indeed call rb_check_safe_obj function and it apparently is whiny.

Setting $VERBOSE to nil is the same as running with RUBYOPT=-W0.

Top comments (1)

Collapse
 
bertocq profile image
BertoCQ

@epigene thank you very much for this article!

It made really easy to figure out what was going on and how to solve it with a quick google search ๐Ÿ‘๐Ÿฟ

I would suggest to use Kernel#silence_warnings inside of to_s instead. Tested it locally and doesn't seem to have any disadvantage. What do you think?

suggestion