Optional named parameters in Padrino routesJanuary 11, 2015
It is not very well documented and I’m not sure its even is in the docs, but Padrino supports optional named parameters in routes. Just place your parameter inside ordinary parentheses “()” and you are good to go.
A use case could be to load an editor with a post if the named parameter
:id exists and if not create a new post.
get :posts_editor, map: '/posts/editor/(:id)' do if params[:id] @post = Post.find(params[:id]) else @post = Post.new end render('panels_posts_editor') end
of if you prefer to use the
with: option instead
get :posts_editor, map: '/posts/editor', with: '(:id)' do # Route renders like: /posts/editor/(:id) # Code goes here end
It also works when using an
with:array of options, where
:namewould be optional.
get :posts_editor, map: '/posts/editor', with: [:id, '(:name)'] do # Route renders like: /posts/editor/:id/(:name) # Code goes here end
The above examples lets you then use the reverse lookup like this without any errors or problem.
# Without :id <%= link_to('New post', url(:posts_editor)) %> # and with :id <%= link_to('New post', url(:posts_editor, id: 2)) %>