Rails 5在gem railtie中

时间:2018-10-16 15:35:12

标签: ruby-on-rails ruby rubygems ruby-on-rails-5 gemspecs

我们正在为两个共享应用程序编写一个包含多个常见gem的gem。我们希望能够从消费应用程序中在application.rbenviroment.rb/*rb之类的config.fruit_chain.enable_transport = true中进行配置,以有条件地要求使用gem及其动态初始化程序。但是来自普通gem的初始化程序在railtie中的require之后不会运行。我想知道是否有更好的方法

fruit_store / config / application.rb。 (正在使用的应用)

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(我们的宝石)

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。 (相关的普通宝石)

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

0 个答案:

没有答案