ruby-on-railsruby-on-rails-3rubygemsruby-on-rails-3.2railtie

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. I'm basically inserting models into into, plus libraries and a few initializers, in the old Rails app style. My main concern is not knowing exactly in the whole Rails application loading logic where I should best insert them. 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. In the Rails app workflow, it somehow works. 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. 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.


Solution

  • I think what you want is 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.

    So you would have:

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