'In Rails 6, where do I place moneky patch code so that it gets run before the Gem code?
I’m using Ruby 3.0.2 and Rails 6.1.4.4. I have installed a gem, octoshark v 0.3.0, that doesn’t play well with Ruby 3. The gem file is
~/.rvm/gems/ruby-3.0.2@cfs-web/gems/octoshark-0.3.0/lib/octoshark/active_record_extensions.rb
And the specific line is line 5 in its ConnectionHandler.establish_connection method. I want to monkey-patch this method but putting my code into a file, lib/ext/octoshark/active_record_extensions.rb, and then loading it in config/initializers/ext.rb with
Dir.glob(Rails.root.join('lib/ext/**/*.rb')).sort.each do |filename|
require filename
end
But when I start my server, it appears my Octoshark gem code is getting called before the monkey patch code. (I proved this by putting a statement in the “ext.rb” file that would intentionally raise an error). What’s the right way to monkey patch this file?
Edit: Per the suggestion given, I created a file, lib/core_extensions/octoshark/connection_handler.rb, with this
module CoreExtensions
module Octoshark
module ConnectionHandler
def establish_connection(config, **parameters)
Octoshark::ConnectionPoolsManager.reset_connection_managers!
super(config, **parameters)
end
end
end
end
Solution 1:[1]
A simple way is to make a monkeypatch folder inside your initializers:
$ mkdir config/initializers/monkeypatch
Then you can separate by file:
$ touch config/initializers/monkeypatch/string.rb
$ touch config/initializers/monkeypatch/array.rb
$ touch config/initializers/monkeypatch/hash.rb
Solution 2:[2]
I would recommend looking up the exact error you have. Most likely other gems have encountered the same issue and there could be a fix there.
Generally speaking though, you would just add an initializer for it and put your patch there. Though if it breaks before it is even initialized then that would be interesting and you could probably put it near the top of the config/application.rb (you might need to experiment with exactly where).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blair Anderson |
| Solution 2 | Nuclearman |
