Unable to monkey-patch a subroutine of a plugin to be loaded in Mojolicious framework #2057
-
I've a module named Mojolicious::Plugin::SecureCORS, which will be loaded as a plugin by Mojolicious app. Now my requirement is to monkey-patch one of its subroutines. So, when I monkey-patched it, the monkey-patched one is not being executed. Also monkey-patching is done in a separate file and loaded this module before loading the module via plugin. The issue I'm facing is the original subroutine from loaded plugin is only getting called and not the patched one So the question is how to monkey-patch a subroutine of a module which will be loaded as a plugin. Is it like the module loaded by plugin disregard monkey-patching / symbol table or it just caches it i.e. whatever is there in registry() subroutine, then further method would be called from loaded plugin only?. Code Ex:
`Use Base::MonkeyPatchesCORS; sub startup {
}
use strict; no strict 'refs'; my $cors_getopt = &Mojolicious::Plugin::SecureCORS::_getopt; I would appreciate any help. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You might have a better time if you subclass the plugin you're wanting to mess with: # in myapp.git/lib/Mojolicious/Plugin/MonkeySecureCORS.pm
package Mojolicious::Plugin::MonkeySecureCORS;
# a lengthy comment explaining what you were thinking when you
# wrote this jank layer, maybe link back to a bug-report on the upstream
# version of the plugin so people know when they can stop using this
# shim
use Mojo::Base 'Mojolicious::Plugin::SecureCORS';
sub the_thing_i_want_to_replace {
warn "monkey pull lever, monkey get banana"
return $_[0]->NEXT::the_thing_i_want_to_replace(...);
}
1 # Your mojo app's startup:
$self->plugin('Mojolicious::Plugin::MonkeySecureCORS'); |
Beta Was this translation helpful? Give feedback.
Thanks for your answer. So I had to just use
use Mojo::Base 'Mojolicious::Plugin::SecureCORS';
and then to override/mokeypatch any subroutine of SecureCORS plugin usedmy $cors_getopt = &Mojolicious::Plugin::SecureCORS::_getopt; *{'Mojolicious::Plugin::SecureCORS::getopt'} = sub { my %opt = &$cors_getopt(@); $opt{'origin'} = get_allowed_origin(); return %opt; };
This way I was able to do it.
Thanks for your help!