简体   繁体   English

Railtie:如何访问初始化程序和lib加载钩子?

[英]Railtie: How to access initializer and lib loading hooks?

I am developing a gem for my Rails application, which be loaded into it through Railtie. 我正在为我的Rails应用程序开发一个gem,它将通过Railtie加载到它中。 I'm basically inserting models into into, plus libraries and a few initializers, in the old Rails app style. 我基本上是在旧的Rails应用程序风格中插入模型,加上库和一些初始化器。 My main concern is not knowing exactly in the whole Rails application loading logic where I should best insert them. 我主要担心的是在整个Rails应用程序加载逻辑中并不完全知道我应该最好插入它们。 My requirement for it is: the gem initializers have to be loaded before the app initializers, same thing with the libs, and the initializers access lib information. 我的要求是:gem初始化器必须在app初始化器之前加载,与libs相同,初始化器访问lib信息。 In the Rails app workflow, it somehow works. 在Rails应用程序工作流程中,它以某种方式工作。 My short-term workaround was the following: 我的短期解决方法如下:

module Gemname
  def self.initialize_railtie
    ActiveSupport.on_load :active_record do
      require 'gemname/lib'
      require 'gemname/initializers'
    end
  end
  class Railtie < Rails::Railtie
  initializer 'gemname.insert_into_app' do
    Gemfile.initialize_railtie
  end
end 

So this way, I'm sure that the libs are loaded before the initializers. 所以这样,我确定在初始化器之前加载了libs。 Just I'm pretty sure there is a better way to do it, namely, access some railtie hook which allows me to load my libs with the app libs and the initializers with the app initializers. 我非常确定有更好的方法,即访问一些铁路钩子,这允许我使用应用程序库加载我的库,使用应用程序初始化器加载初始化程序。 Just I can't seem to be able to find them. 我似乎无法找到它们。

I think what you want is config.after_initialize . 我想你想要的是config.after_initialize According to here : 根据这里

Last configurable block to run. 要运行的最后一个可配置块。 Called after frameworks initialize. 在框架初始化后调用。

and here : 在这里

after_initialize: Run directly after the initialization of the application, but before the application initializers are run. after_initialize:在应用程序初始化之后直接运行,但在运行应用程序初始化程序之前。

So you would have: 所以你会:

module Gemname
  class MyCoolRailtie < ::Rails::Railtie
    config.after_initialize do
      require 'gemname/lib'
      require 'gemname/initializers'
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM