6. Routes with conditions
Matching
match(quot;/articlesquot;) do
with(:controller => quot;articlesquot;) do
match(quot;/:titlequot;, :title => /[a-z]+/).
to(:action => quot;with_titlequot;)
match(quot;/:idquot;).to(:action => quot;with_idquot;)
end
end
/articles/Hello_world => with_title
/articles/123 => with_id
7. More conditions
Matching
Merb::Router.prepare do
match(:domain => quot;blogofawesomeness.comquot;) do
match(quot;/the-daily-awesomequot;, :method => quot;getquot;).
to(:articles)
# Any other route...
end
end
8. The subdomain problem
match(:subdomain => /(.*)/).
to(:account => quot;:subdomain[1]quot;) do
# application routes here...
end
15. Resource routes
Matching
resources :articles
/articles GET => index
/articles POST => create
/articles/new GET => new
/articles/:id GET => show
/articles/:id PUT => update
/articles/:id DELETE => destroy
/articles/:id/edit GET => edit
/articles/:id/delete GET => delete
16. and you can nest them
Matching
resources :articles do
resources :comments
end
Generating
link_to quot;view commentquot;, url(:article_comment,
comment.article_id, comment.id)
17. Nested multiple times
resources :articles do
resources :comments
end
resources :songs do
resources :comments
end
resources :photos do
resources :comments
end
19. Nah... how about this?
link_to quot;view commentquot;,
resource(comment.commentable, comment)
20. Some more examples
resources :users do
resources :comments
end
Generating
resource(@user) resource(@user, :comments)
vs. vs.
url(:user, @user) url(:user_comments, @user)
resource @user, @comment
vs.
url(:user_comment, @user, @comment)
21. Oh yeah...
match(quot;/:projectquot;) do
resources :tasks
end
- While currently at /awesome/tasks
resource(@task)
=> /awesome/tasks/123
resource(@task, :project => quot;wootquot;)
=> /woot/tasks/123
24. It works as a block too
Matching
identify(Article=>:permalink, User=>:login) do
resources :users do
resources :articles
end
end
Generating
resource(@user, @article)
/users/carl/articles/hello-world
31. Works great for plugins
def protect(&block)
protection = Proc.new do |request, params|
if request.session.authenticated?
params
else
redirect quot;/loginquot;
end
end
defer(protection, &block)
end