Openhood

Add routes at runtime on Rails 3

Image by by Javier García on unsplash

Sometimes you just want to take the forbidden path. We had the case quite recently, while testing a Paypal integration. We did want to add a route to a fake Paypal service with a link back to our website after succesful payment, but at the same time we didn’t want to polute our routes.rb just for test purpose. Hopefully, it’s still possible to add routes at runtime even on Rails 3. The issue is calling Rails::Application.routes.draw clears all existing routes and after that no further route can be defined. The solution is inspired by how Rails is doing route reloading:

begin
  _routes = Rails::Application.routes
  _routes.disable_clear_and_finalize = true
  _routes.clear!
  Rails::Application.routes_reloader.paths.each{ |path| load(path) }
  _routes.draw do
    # here you can add any route you want
    get "/test#{rand(1000000)}", :to => "sessions#new"
  end
  ActiveSupport.on_load(:action_controller) {_routes.finalize! }
ensure
  _routes.disable_clear_and_finalize = false
end

Please note that using Rails::Application is deprecated and that you should replace it with MyApplicationName::Application everywhere instead. Happy hacking ;)

Copyright © 2024 Openhood SARL