Loading…
The Case Against Monkey Patching, From a Rails Core Team Member
2023-10-18
- Source
- Shopify
- Published
- Added to Yomu
Summary
The post argues that Ruby monkey patches—global changes to existing objects or libraries—should be used sparingly because they are brittle, dangerous, and often unnecessary. They can make Rails and Ruby upgrades harder by depending on private APIs, leave applications exposed to vulnerabilities if security fixes are not mirrored, and accumulate poorly documented technical debt. One Shopify example, activerecord-pedant-adapter, changes Active Record’s MySQL2Adapter so database connections report MySQL query warnings; upstreaming that behavior into Rails allowed the gem to be archived and the patch removed. The recommended alternative is to investigate whether an upgrade or documentation resolves the issue, fix genuine defects upstream, and, when patching is unavoidable, document and test it while maintaining a removal plan.
Context
Monkey patches alter library behavior globally and can complicate Rails and Ruby upgrades, create security exposure when upstream fixes are not mirrored, accumulate technical debt, and change behavior for callers unexpectedly. The post also addresses existing codebases containing legacy patches that obstruct upgrades and require deliberate cleanup.
Approach / What changed
Prefer upgrading or consulting documentation before patching, and send genuine fixes or issues upstream. For unavoidable patches, clearly document their purpose, test their behavior, and create a removal plan. Existing patches should be inventoried, moved into a discoverable location, assessed for upstreaming or obsolescence, and removed individually.
Takeaways
- Patching private or internal Rails APIs can break during upgrades without deprecation warnings, making rewrites tedious and potentially blocking an upgrade.
- Shopify upstreamed query-warning behavior from activerecord-pedant-adapter into Rails, allowing the gem to be archived and the application patch removed.
- Unavoidable monkey patches should be documented, thoroughly tested, and tracked with a removal TODO or issue so they do not become forgotten legacy code.