Search code examples
ruby-on-railsruby-on-rails-2

Code runs well inside an initializer but breaks when called from another class


I have a little monkey patch to deal with some ruby 2.7 warning that are not needed, when I execute the code directly from the an initializer file it works pretty well, but when I move the code to the lib dir and call it from an initializer using include all tests start to break

module Extensions
  module BigDecimalFormatWarningSuppressor
    # NOTE: this API comes from ActiveSupport::NumericWithFormat, the last ancestor prepended to
    # BigDecimal.
    def to_s(args)
      original_verbosity = $VERBOSE
      $VERBOSE = nil
      v = super
      $VERBOSE = original_verbosity
      v
    end
  end
end

BigDecimal.prepend(Extensions::BigDecimalFormatWarningSuppressor)

So in an effort to get all monkeypatches in a single place we started moving them to a dir in lib(extensions) and started calling them inside an initializer using a simple include.

include Extensions::BigDecimalFormatWarningSuppressor

Problem is: when I run this code directly inside of the initializer everything works as a charm, but when I run the code as it is above a lot of tests start breaking with:

/path/lib/extensions/big_decimal_format_warning_suppressor.rb:14:in `to_s'
/path/lib/extensions/big_decimal_format_warning_suppressor.rb:14:in `to_s': wrong number of arguments (given 2, expected 0) (ArgumentError)

Solution

  • I just had to remove the include from the initializer and call the class directly, guess it was messing up with the BigDecimal class.

    Also removed the prepend part on the extensions module, figure the rails autoload would take care of everything sice it's called on the initializer.