Skip to content
This repository
Browse code

Add support for optional root segments containing slashes

Optional segments with a root scope need to have the leading slash
outside of the parentheses, otherwise the generated url will be empty.
However if the route has non-optional elements then the leading slash
needs to remain inside the parentheses otherwise the generated url
will have two leading slashes, e.g:

Blog::Application.routes.draw do
  get '/(:category)', :to => 'posts#index', :as => :root
  get '/(:category)/author/:name', :to => 'posts#author', :as => :author
end

$ rake routes
  root GET /(:category)(.:format)              posts#index
author GET (/:category)/author/:name(.:format) posts#author

This change adds support for optional segments that contain a slash,
allowing support for urls like /page/2 for the root path, e.g:

Blog::Application.routes.draw do
  get '/(page/:page)', :to => 'posts#index', :as => :root
end

$ rake routes
root GET /(page/:page)(.:format) posts#index

Fixes #7073
(cherry picked from commit d8745de)
  • Loading branch information...
commit 71d274dbbb3972afb7808a84ecdd005d95107212 1 parent e23ec4c
Andrew White authored July 17, 2012
2  actionpack/lib/action_dispatch/routing/mapper.rb
@@ -238,7 +238,7 @@ def default_action
238 238
       # for root cases, where the latter is the correct one.
239 239
       def self.normalize_path(path)
240 240
         path = Journey::Router::Utils.normalize_path(path)
241  
-        path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^/]+\)$}
  241
+        path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
242 242
         path
243 243
       end
244 244
 
26  actionpack/test/dispatch/routing_test.rb
@@ -2755,3 +2755,29 @@ def app; Routes end
2755 2755
   end
2756 2756
 end
2757 2757
 
  2758
+class TestOptionalRootSegments < ActionDispatch::IntegrationTest
  2759
+  stub_controllers do |routes|
  2760
+    Routes = routes
  2761
+    Routes.draw do
  2762
+      get '/(page/:page)', :to => 'pages#index', :as => :root
  2763
+    end
  2764
+  end
  2765
+
  2766
+  def app
  2767
+    Routes
  2768
+  end
  2769
+
  2770
+  include Routes.url_helpers
  2771
+
  2772
+  def test_optional_root_segments
  2773
+    get '/'
  2774
+    assert_equal 'pages#index', @response.body
  2775
+    assert_equal '/', root_path
  2776
+
  2777
+    get '/page/1'
  2778
+    assert_equal 'pages#index', @response.body
  2779
+    assert_equal '1', @request.params[:page]
  2780
+    assert_equal '/page/1', root_path('1')
  2781
+    assert_equal '/page/1', root_path(:page => '1')
  2782
+  end
  2783
+end

0 notes on commit 71d274d

Please sign in to comment.
Something went wrong with that request. Please try again.