From 8dc784292b67b842e437632a4ff883572ff97a3e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 24 Sep 2018 11:30:15 -0700 Subject: Eagerly build the routing helper module after routes are committed This commit eagerly builds the route helper module after the routes have been drawn and finalized. This allows us to cache the helper module but not have to worry about people accessing the module while route definition is "in-flight", and automatically deals with cache invalidation as the module is regenerated anytime someone redraws the routes. The restriction this commit introduces is that the url helper module can only be accessed *after* the routes are done being drawn. Refs #24554 and #32892 --- .../action_dispatch/testing/assertions/routing.rb | 37 ++++++++++++++++------ 1 file changed, 27 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch/testing/assertions') diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index af41521c5c..0e8712f8d9 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -138,6 +138,20 @@ module ActionDispatch assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message) end + # Provides a hook on `finalize!` so we can mutate a controller after the + # route set has been drawn. + class WithRouting < ActionDispatch::Routing::RouteSet # :nodoc: + def initialize(&block) + super() + @block = block + end + + def finalize! + super + @block.call self + end + end + # A helper to make it easier to test different route configurations. # This method temporarily replaces @routes with a new RouteSet instance. # @@ -152,16 +166,19 @@ module ActionDispatch # end # def with_routing - old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new - if defined?(@controller) && @controller - old_controller, @controller = @controller, @controller.clone - _routes = @routes - - @controller.singleton_class.include(_routes.url_helpers) - - if @controller.respond_to? :view_context_class - @controller.view_context_class = Class.new(@controller.view_context_class) do - include _routes.url_helpers + old_routes = @routes + old_controller = nil + @routes = WithRouting.new do |_routes| + if defined?(@controller) && @controller + old_controller, @controller = @controller, @controller.clone + _routes = @routes + + @controller.singleton_class.include(_routes.url_helpers) + + if @controller.respond_to? :view_context_class + @controller.view_context_class = Class.new(@controller.view_context_class) do + include _routes.url_helpers + end end end end -- cgit v1.2.3