Add routes in Rails dynamically at runtime

After poking around some more, I answered my question in my previous post — “when I add a route at runtime, do they add to the route list or replace existing ones?”  The answer is that they are added to the route list.  So here’s the code to add the route once by checking to see if it already exists.  If not, the route is added, if it does exist, we verify that the controller, method, and verb are identical.

  # Add the route if it doesn't exist.
  # Example: add_route('post', 'sign_in', 'users', 'sign_in') 
  def add_route(verb, url, controller, method)
    route = controller + '_' + method
    if Rails.application.routes.named_routes.routes[route.to_sym].nil?
      Rails.application.routes.disable_clear_and_finalize = true
      Rails.application.routes.draw do
        meth = method(verb.downcase)"/#{url}" => "#{controller}##{method}", :as => "#{controller}_#{method}")
      # Check that we're adding the same verb and route.
      # TODO: Verify the URL is the same too.
      route_verb = Rails.application.routes.named_routes.routes[route.to_sym].verb
      unless route_verb.to_s.upcase =~ /#{verb.upcase}/
        raise "Attempting to use a different verb #{verb} for route #{controller}_#{method}."




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s