ruby-on-rails-4rails-engines

Is before_action in application controller executed before routes.rb and models are loaded?


For a before_action in Rails engine's application controller, when a user requests an action from the engine, is the before_action executed before engine's routes.rb and models are loaded (or some procedure/tool which allows us to find out the executing order. Debug seems to be skipping the routes.rb and model definitions)?

class ApplicationController < ApplicationController

    before_action :setup_some_variable
    ..........
end

The purpose of setup_some_variable is to set variables which will be used in routes.rb and models in the engine.

Or an engines's routes.rb and models are loaded when the main_app is launched. Here the main app's `routes.rb' mounting a Rails engine:

Myapp::Application.routes.draw do

  mount MyEngine::Engine => "/my_engine"

end

Solution

  • Routes are loaded on application startup, and models are loaded using the Autoloader so the first time they are referenced in your code.

    before_action runs before any controller action is run, so after the request has been routed to the correct controller action.

    The Rails booting process is documented here: https://github.com/rails/rails/blob/master/railties/lib/rails/application.rb#L37