Add routes at runtime on Rails 3

Posted in : rails and rails 3

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:

  _routes = Rails::Application.routes
  _routes.disable_clear_and_finalize = true
  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"
  ActiveSupport.on_load(:action_controller) { _routes.finalize! }
  _routes.disable_clear_and_finalize = false

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

blog comments powered by Disqus