Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I automatically run some code when my gem is activated?
    text
    copied!<p>I created a gem that is essentially a plugin/extension to an existing Ruby app. The app has some consideration for this using bundler; it automatically executes <code>Bundle.require :misc</code> when starting up.</p> <p>I've added my Gem to the <code>:misc</code> group in the <code>Gemfile</code> and my gem is getting added to the load path as expected. The challenge is that in order for my extension to work correctly I need to monkey patch some existing classes.</p> <p>All my monkey patch code is contained in a ruby file in the gem (let's say <code>lib/mygem/patch.rb</code>). If I manually edit the source of the base app to call <code>require 'mygem/patch'</code> after the existing line for <code>Bundle.require :misc</code> then everything works great. However that is sloppy and requires editing the installed gem for the base app every time I reinstall gems or move to a new machine.</p> <pre><code># Currently I can load my gem and execute the monkey patch in 2 lines gem 'mygem' require 'mygem/patch' # Or with bundler (mygem is in the :misc group) Bundle.require :misc require 'mygem/patch' # I want to achieve the same result in only one line gem 'mygem' # or Bundle.require :misc </code></pre> <p>I want to automatically run some code from inside my extension gem whenever it is activated from the base application, without having to manually require the file. The solution should work both when the gem is individually activated with a <code>gem 'mygem'</code> statement, or as part of a bundle group as in <code>Bundle.require :misc</code>. </p> <p>Is this possible? Is there a better pattern to address monkey-patching from within a "plugin/extension" gem?</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload