Skip to content

Commit

Permalink
Add after_routes_loaded hook for Engines to trigger code after appl…
Browse files Browse the repository at this point in the history
…ication routes have been loaded (rails#46539)

* Add after_routes_loaded hook

This hook can be used to trigger engine behavior that should only happen
after application routes have been loaded (or reloaded).

* Add changelog entry

* Add note about new after_routes_loaded railtie config to guides

[Rafael Mendonça França + Chris Salzberg]
  • Loading branch information
shioyama committed Nov 22, 2022
1 parent d666a39 commit 6496226
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions guides/source/configuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,16 @@ config.after_initialize do
end
```

### `config.after_routes_loaded`

Takes a block which will be run after Rails has finished loading the application routes. This block will also be run whenever routes are reloaded.

```ruby
config.after_routes_loaded do
# Code that does something with Rails.application.routes
end
```

#### `config.allow_concurrency`

Controls whether requests should be handled concurrently. This should only
Expand Down
12 changes: 12 additions & 0 deletions railties/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
* Add `after_routes_loaded` hook to `Rails::Railtie::Configuration` for
engines to add a hook to be called after application routes have been
loaded.

```ruby
MyEngine.config.after_routes_loaded do
# code that must happen after routes have been loaded
end
```

*Chris Salzberg*

* Send 303 See Other status code back for the destroy action on newly generated
scaffold controllers.

Expand Down
1 change: 1 addition & 0 deletions railties/lib/rails/application/finisher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ def self.complete(_state)
# some sort of reloaders dependency support, to be added.
require_unload_lock!
reloader.execute
ActiveSupport.run_load_hooks(:after_routes_loaded, self)
end
end

Expand Down
5 changes: 5 additions & 0 deletions railties/lib/rails/railtie/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ def after_initialize(&block)
ActiveSupport.on_load(:after_initialize, yield: true, &block)
end

# Called after application routes have been loaded.
def after_routes_loaded(&block)
ActiveSupport.on_load(:after_routes_loaded, yield: true, &block)
end

# Array of callbacks defined by #to_prepare.
def to_prepare_blocks
@@to_prepare_blocks ||= []
Expand Down

0 comments on commit 6496226

Please sign in to comment.