2

We are writing a gem that includes multiple common gems for a couple of our shared apps. We want to be able to have a config in application.rb or enviroment.rb/*rb something like config.fruit_chain.enable_transport = true from the consuming app to conditionally require a gem and it's initializer dynamically. But the initializer from common gem does not run after require in a railtie. I wondered if there is a better way to do this

fruit_store/config/application.rb . (consuming app)

module FruitStore
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    config.fruit_chain.enable_transport = true
  end
end

fruit_chain/lib/fruit_chain.rb (Our gem)

require analytic 
- require transport      <----- removed this so it dose not autoload
require marketing
...

module FruitChain
end

fruit_chain/lib/fruit_chain/rails/railtie.rb

module FruitChain
  module Rails
    class Railtie < ::Rails::Railtie
      config.fruit_chain = ActiveSupport::OrderedOptions.new
      config.fruit_chain.enable_transport = false

      config.before_initialize do |app|
        if app.config.fruit_chain.enable_transport
          Kernel.require 'transport'             <--- this require the gem correct and load it up         

          app.initializers.find{ 
            |a| a.name === 'transport.configure'
          }.run <--- transport.configure initializer doesn't kick off
        end        
      end
    end
  end
end

transport/lib/transport.rb . (Dependent common gem)

require transport/rails/railtie 
...

module Transport
end

transport/lib/transport/rails/railtie.rb

module Transport
  module Rails
    class Railtie < ::Rails::Railtie
      initializer 'transport.configure' do |app|
      ...
      end
    end
  end
end
AirWick219
  • 894
  • 8
  • 27
  • Please update your code so that the Modules are constants. Also not sure what `enable_transport` is but why not just require the gem there? e.g. `def enable_transport=(val); require 'transport' if val && !defined?(Transport); end` – engineersmnky Oct 17 '18 at 17:26
  • `enable_transport` is a config option that we added in `fruit_chain/lib/fruit_chain/rails/railtie.rb` so that the consuming app can just do `config.fruit_chain.enable_transport = true` in the `application.rb`. Basically we need a way to config to require the `transport` gem or not in our gem. – AirWick219 Oct 17 '18 at 18:03

0 Answers0