SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
Merb Plumbing
    The Router
Who am I?
Some simple routes
Matching
 Merb::Router.prepare do
  match(quot;/signupquot;).to(
   :controller => quot;usersquot;, :action => quot;newquot;
  ).name(:signup)
 end


Generating
 url(:signup) =>   /signup
Routes with variables
Matching
 match(quot;/articles/:year/:month/:day/:titlequot;).to(
  :controller => quot;articlesquot;, :action => quot;showquot;
 ).name(:article)


Generating
 url(:article, :year => 2008, :month => 07,
   :day => 22, :title => quot;Awesomenessquot;)


    /articles/2008/07/22/Awesomeness
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
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
The subdomain problem


  match(:subdomain => /(.*)/).
  to(:account => quot;:subdomain[1]quot;) do
    # application routes here...
end
Optional path segments
Matching
 match(quot;/articles(/:year(/:month(/:day)))/:titlequot;).
 to(:controller => quot;articlesquot;, :action => quot;showquot;).
 name(:article)

Generating
 /articles/Hello => { :title => “Hello” }

/articles/2008/07/Hello
  => { :year => 2008, :month => “07”
       :title => “Hello” }
... and generation still works!

 url(:article, :title => quot;Helloquot;)

 url(:article, :year => quot;2008quot;, :title => quot;Helloquot;)

 url(:article, :year => quot;2008quot;, :month => quot;07quot;,
               :title => quot;Helloquot;)

 url(:article, :year => quot;2008quot;, :month => quot;07quot;,
               :day => quot;22quot;, :title => quot;Helloquot;)
Getting Fancy

Matching
  match(quot;(:pref)/:file(.:format)quot;, :pref => quot;.*quot;).
   to(:controller => quot;cmsquot;).name(:page)



/hi         => { :file => “hi” }
/hi.xml     => { :file => “hi”, :format => “xml”}
/path/to/hi => { :pref => “/path/to”, :file => “hi }
And you can still generate it
 url(:page, :file => quot;hiquot;)


  /hi

url(:page, :pref => quot;/path/toquot;, :file => quot;hiquot;)


  /path/to/hi

url(:page, :pref => quot;/helloquot;, :file => quot;worldquot;,
           :format => quot;mp3quot;)


 /hello/world.mp3
The default route


def default_route(params = {}, &block)
  match(quot;/:controller(/:action(/:id))(.:format)quot;).
  to(params, &block).name(:default)
end
AWESOME!
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
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)
Nested multiple times
resources :articles do
  resources :comments
end

resources :songs do
  resources :comments
end

resources :photos do
  resources :comments
end
and... generating?
 link_to quot;view commentquot;,
   comment.commentable.is_a?(Article) ?
   url(:article_comment, comment.commentable.id,
   comment.id) : comment.commentable.is_a?(Song) ?
   url(:song_comment, comment.commentable.id,
   comment.id) : url(:photo_comment,
   comment.commentable.id, comment.id)



wha...?
Nah... how about this?


link_to quot;view commentquot;,
  resource(comment.commentable, comment)
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)
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
AWESOME!
Friendly URLs

  Matching
resources :users, :identify => :name



Generating
 resource(@user) # => /users/carl
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
AWESOME!
Redirecting legacy URLs


Old:   /articles/123-hello-world

New:   /articles/Hello_world
Handle it in the controller?


match(quot;/articles/:idquot;).
  to(:controller => quot;articlesquot;, :action => quot;showquot;)
Try to do it with Regexps?


match(quot;/articles/:idquot;, :id => /^d+-/).
  to(:controller => quot;articlesquot;, :action => quot;legacyquot;)

match(quot;/articles/:urlquot;).
  to(:controller => quot;articlesquot;, :action => quot;showquot;)
Or, add your own logic!
match(quot;/articles/:urlquot;).defer_to do |request, params|

  if article = Article.first(:url => params[:url])
    params.merge(:article => article)
  elsif article = Article.first(:id => params[:url])
    redirect url(:article, article.url)
  else
    false
  end

end
Authentication works too


match(quot;/secretquot;).defer_to do |request, params|
  if request.session.authenticated?
    params
  end
end
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
Awesome!


protect.match(quot;/adminquot;) do
 # ... admin routes here
end
Thank you
(Awesome!)

Mais conteúdo relacionado

Mais procurados

Paquetes y precios h go
Paquetes y precios h goPaquetes y precios h go
Paquetes y precios h go
imtpae17
 
ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4
ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4
ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4
Dimitris Psounis
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
Joao Lucas Santana
 
Letter and email_phrases
Letter and email_phrasesLetter and email_phrases
Letter and email_phrases
Emilie Baker
 
имидж pr ганелина
имидж pr ганелинаимидж pr ганелина
имидж pr ганелина
eganelina
 
Normativa riferimento 81 08
Normativa riferimento 81 08Normativa riferimento 81 08
Normativa riferimento 81 08
sebaber
 
Weeks3 5 cs_sbasics
Weeks3 5 cs_sbasicsWeeks3 5 cs_sbasics
Weeks3 5 cs_sbasics
Evan Hughes
 

Mais procurados (20)

Laboratoire nomade 2015 mai
Laboratoire nomade 2015 maiLaboratoire nomade 2015 mai
Laboratoire nomade 2015 mai
 
Paquetes y precios h go
Paquetes y precios h goPaquetes y precios h go
Paquetes y precios h go
 
ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4
ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4
ΠΛΗ31 ΤΥΠΟΛΟΓΙΟ ΕΝΟΤΗΤΑΣ 4
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
Know001
Know001Know001
Know001
 
goviral publisher info (DE 0611) PDF
goviral publisher info (DE 0611) PDFgoviral publisher info (DE 0611) PDF
goviral publisher info (DE 0611) PDF
 
Letter and email_phrases
Letter and email_phrasesLetter and email_phrases
Letter and email_phrases
 
Digital Opportunities: Steve Wind-Mozley, director of digital, Virgin Media B...
Digital Opportunities: Steve Wind-Mozley, director of digital, Virgin Media B...Digital Opportunities: Steve Wind-Mozley, director of digital, Virgin Media B...
Digital Opportunities: Steve Wind-Mozley, director of digital, Virgin Media B...
 
Clinical Trials in The Cloud
Clinical Trials in The CloudClinical Trials in The Cloud
Clinical Trials in The Cloud
 
U.S. News | National News
U.S. News | National NewsU.S. News | National News
U.S. News | National News
 
имидж pr ганелина
имидж pr ганелинаимидж pr ганелина
имидж pr ганелина
 
Apps Market Research
Apps Market ResearchApps Market Research
Apps Market Research
 
V8n1a12
V8n1a12V8n1a12
V8n1a12
 
Couch Db.0.9.0.Pub
Couch Db.0.9.0.PubCouch Db.0.9.0.Pub
Couch Db.0.9.0.Pub
 
Normativa riferimento 81 08
Normativa riferimento 81 08Normativa riferimento 81 08
Normativa riferimento 81 08
 
Kuwait - Introduction
Kuwait - IntroductionKuwait - Introduction
Kuwait - Introduction
 
Weeks3 5 cs_sbasics
Weeks3 5 cs_sbasicsWeeks3 5 cs_sbasics
Weeks3 5 cs_sbasics
 
אומנות הלחימה גדעון אונה
אומנות הלחימה גדעון אונהאומנות הלחימה גדעון אונה
אומנות הלחימה גדעון אונה
 
Motherloss
MotherlossMotherloss
Motherloss
 
Locality in long-distance phonotactics: evidence for modular learning
Locality in long-distance phonotactics: evidence for modular learningLocality in long-distance phonotactics: evidence for modular learning
Locality in long-distance phonotactics: evidence for modular learning
 

Destaque (8)

Frozen Rails Slides
Frozen Rails SlidesFrozen Rails Slides
Frozen Rails Slides
 
MLS118 Session 1 July 2011
MLS118 Session 1 July 2011MLS118 Session 1 July 2011
MLS118 Session 1 July 2011
 
Changing educators one video game at a time
Changing educators one video game at a timeChanging educators one video game at a time
Changing educators one video game at a time
 
Attitude, Belief And Commitment
Attitude,  Belief And  CommitmentAttitude,  Belief And  Commitment
Attitude, Belief And Commitment
 
NIE hosts Japet
NIE hosts JapetNIE hosts Japet
NIE hosts Japet
 
ICT for Meaningful Learning - Session01b
ICT for Meaningful Learning - Session01bICT for Meaningful Learning - Session01b
ICT for Meaningful Learning - Session01b
 
Revised version of TEDxYouth@Singapore talk: Changing educators one video gam...
Revised version of TEDxYouth@Singapore talk: Changing educators one video gam...Revised version of TEDxYouth@Singapore talk: Changing educators one video gam...
Revised version of TEDxYouth@Singapore talk: Changing educators one video gam...
 
DED107 Session03
DED107 Session03DED107 Session03
DED107 Session03
 

Semelhante a Merb Pluming - The Router

Rails 3 And The Real Secret To High Productivity Presentation
Rails 3 And The Real Secret To High Productivity PresentationRails 3 And The Real Secret To High Productivity Presentation
Rails 3 And The Real Secret To High Productivity Presentation
railsconf
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
Wen-Tien Chang
 
ApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub ImplementationApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub Implementation
David Calavera
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 

Semelhante a Merb Pluming - The Router (20)

Rails 3 And The Real Secret To High Productivity Presentation
Rails 3 And The Real Secret To High Productivity PresentationRails 3 And The Real Secret To High Productivity Presentation
Rails 3 And The Real Secret To High Productivity Presentation
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009
 
Merb jQuery
Merb jQueryMerb jQuery
Merb jQuery
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?
 
merb.intro
merb.intromerb.intro
merb.intro
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
ApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub ImplementationApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub Implementation
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
 
Plone Interactivity
Plone InteractivityPlone Interactivity
Plone Interactivity
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Merb Pluming - The Router

  • 1. Merb Plumbing The Router
  • 3.
  • 4. Some simple routes Matching Merb::Router.prepare do match(quot;/signupquot;).to( :controller => quot;usersquot;, :action => quot;newquot; ).name(:signup) end Generating url(:signup) => /signup
  • 5. Routes with variables Matching match(quot;/articles/:year/:month/:day/:titlequot;).to( :controller => quot;articlesquot;, :action => quot;showquot; ).name(:article) Generating url(:article, :year => 2008, :month => 07, :day => 22, :title => quot;Awesomenessquot;) /articles/2008/07/22/Awesomeness
  • 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
  • 9. Optional path segments Matching match(quot;/articles(/:year(/:month(/:day)))/:titlequot;). to(:controller => quot;articlesquot;, :action => quot;showquot;). name(:article) Generating /articles/Hello => { :title => “Hello” } /articles/2008/07/Hello => { :year => 2008, :month => “07” :title => “Hello” }
  • 10. ... and generation still works! url(:article, :title => quot;Helloquot;) url(:article, :year => quot;2008quot;, :title => quot;Helloquot;) url(:article, :year => quot;2008quot;, :month => quot;07quot;, :title => quot;Helloquot;) url(:article, :year => quot;2008quot;, :month => quot;07quot;, :day => quot;22quot;, :title => quot;Helloquot;)
  • 11. Getting Fancy Matching match(quot;(:pref)/:file(.:format)quot;, :pref => quot;.*quot;). to(:controller => quot;cmsquot;).name(:page) /hi => { :file => “hi” } /hi.xml => { :file => “hi”, :format => “xml”} /path/to/hi => { :pref => “/path/to”, :file => “hi }
  • 12. And you can still generate it url(:page, :file => quot;hiquot;) /hi url(:page, :pref => quot;/path/toquot;, :file => quot;hiquot;) /path/to/hi url(:page, :pref => quot;/helloquot;, :file => quot;worldquot;, :format => quot;mp3quot;) /hello/world.mp3
  • 13. The default route def default_route(params = {}, &block) match(quot;/:controller(/:action(/:id))(.:format)quot;). to(params, &block).name(:default) 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
  • 18. and... generating? link_to quot;view commentquot;, comment.commentable.is_a?(Article) ? url(:article_comment, comment.commentable.id, comment.id) : comment.commentable.is_a?(Song) ? url(:song_comment, comment.commentable.id, comment.id) : url(:photo_comment, comment.commentable.id, comment.id) wha...?
  • 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
  • 23. Friendly URLs Matching resources :users, :identify => :name Generating resource(@user) # => /users/carl
  • 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
  • 26. Redirecting legacy URLs Old: /articles/123-hello-world New: /articles/Hello_world
  • 27. Handle it in the controller? match(quot;/articles/:idquot;). to(:controller => quot;articlesquot;, :action => quot;showquot;)
  • 28. Try to do it with Regexps? match(quot;/articles/:idquot;, :id => /^d+-/). to(:controller => quot;articlesquot;, :action => quot;legacyquot;) match(quot;/articles/:urlquot;). to(:controller => quot;articlesquot;, :action => quot;showquot;)
  • 29. Or, add your own logic! match(quot;/articles/:urlquot;).defer_to do |request, params| if article = Article.first(:url => params[:url]) params.merge(:article => article) elsif article = Article.first(:id => params[:url]) redirect url(:article, article.url) else false end end
  • 30. Authentication works too match(quot;/secretquot;).defer_to do |request, params| if request.session.authenticated? params end end
  • 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