How to monkey patch a class (aka static) method in Rails and a common bug

I made this magic monkey patch to inform if the schema cache is really loaded.

However, loaded still does not mean it’s used. I contributed this rails/rails commit for that.

Here’s the code being patched:

Do you see the subtle bug in the original, broken version?

Scroll down to see the explanation.


Original Broken Version

  module ConnectionAdapters
    class SchemaCache
      singleton_class.send(:alias_method, :old_load_from, :load_from)

      # Remove this once Rails is upgraded to 7.0 when this fix is available:
      # https://github.com/rails/rails/commit/9f9c1bf79eee9fd0d3cf059916e3a613d3cc4cbb
      def self.load_from(filename)
        old_load_from(filename)
        Rails.logger.info "Loaded schema cache file #{filename}"
      end
    end
  end
end

Fixed Version

  module ConnectionAdapters
    class SchemaCache
      singleton_class.send(:alias_method, :old_load_from, :load_from)

      # Remove this once Rails is upgraded to 7.0 when this fix is available:
      # https://github.com/rails/rails/commit/9f9c1bf79eee9fd0d3cf059916e3a613d3cc4cbb
      def self.load_from(filename)
        result = old_load_from(filename)
        Rails.logger.info "Loaded schema cache file #{filename}"
        result
      end
    end
  end
end

Summary

Yep, I added a logging statement to confirm the file was loaded, and I returned nil.

So the fix is to save the result in a local variable, then log, then return the result.

:exploding_head:

1 Like