routes: 動的なパスをscopeでまとめる

ユーザごとのURL配下のコンテンツをgetにべた書きしていたので、scopeでまとめた。

before

get ':username', to: 'pages#index', constraints: { format: /()/ }
get ':username/about', to: 'pages#about', constraints: { format: /()/ }
get ':username/announcements', to: 'pages/announcements#index', constraints: { format: /()/}
get ':username/announcements/:id', to: 'pages/announcements#show', constraints: { format: /()/}

に対して

after

scope ':username', constraints:  { format: /()/ } do
get '', to: 'pages#index'
get 'about', to: 'pages#about'
get 'announcements', to: 'pages/announcements#index'
get 'announcements/:id', to: 'pages/announcements#show'
end

こうなる

$ rake routes
GET /:username(.:format) pages#index {:format=>/()/}
about GET /:username/about(.:format) pages#about {:format=>/()/}
announcements GET /:username/announcements(.:format) pages/announcements#index {:format=>/()/}
GET /:username/announcements/:id(.:format) pages/announcements#show {:format=>/()/}

すっきり。