SlideShare a Scribd company logo
1 of 29
Bryan Ray
        http://bryanray.net
The Merb Router
        In Depth ...
Code Repository
  https://github.com/merbday/atlanta
  http://github.com/merbday/atlanta/tree/master/router
Thanks
  Carl Lerche
      Anyone else who has contributed to Merb ...
Simple Routes
Merb::Router.prepare do
  # resources :articles

  # RESTful routes
  # resources :posts
end
Match 3 simple route
Merb::Router.prepare do
  match(quot;/signupquot;).
    to(:controller => quot;usersquot;, :action => quot;newquot;).
    name(:signup)
end

Generating the route:
url(:signup) => /signup
Routes with variables
Merb::Router.prepare do
  match(quot;/articles/:year/:month/:day/:titlequot;).
    to(:controller => quot;articlesquot;, :action => quot;showquot;).
    name(:article)
end
Routes with variables
Generating
url(:article, :year => 2008, :month => 07, :day => 22,
    :title => quot;Awesomenessquot;)

  # => /articles/2008/07/22/Awesomeness
Optional Path Segments
match('/articles(/:year(/:month(/:day)))/:title').
  to(
    :controller => :articles,
    :action => quot;with_optional_segmentsquot;).
  name(:articles)


/articles/hello # => { :title => “hello” }
/articles/2008/12/hello
  # => { :title => “hello”, :year => “2008”,
         :month => “12” }
Routes with conditions
match(quot;/articlesquot;) do
  with(:controller => quot;articlesquot;) do
    match(quot;/:titlequot;, :title => /[a-z]+$/).
      to(:action => quot;with_titlequot;)

    match(quot;/:idquot;, :id => /^[d]+$/).to(:action => quot;with_idquot;)
  end
end


/articles/hello # => Renders the #with_title action
/articles/12    # => Renders the #with_id action
The Subdomain Problem
The end goal
http://<account>.localhost:4000
http://bryan.localhost:4000


Matching inside the router
match(:account => 'bryan').
  to(:controller => 'articles', :action => 'with_account')
The Subdomain Problem
module Merb
  class Request
    def account
      subdomains(0).first
    end
  end
end
#url generation ...
url(:articles, :title => 'hello')
  # => /articles/hello
url(:articles, :year => 2008, :title => 'hello')
  # => /articles/2008/hello
url(:articles, :year => 2008, :month => 12, :title => 'hello')
  # => /articles/2008/12/hello
url(:articles, :year => 2008, :month => 12, :day => 07, :title =>
'hello')
  # => /articles/2008/12/7/hello

# Anonymous Parameters
url(:articles, 2008, 12, 07, :title => 'hello')
  # => /articles/2008/12/7/testing
Default Routes
def default_routes(params = {}, &block)
  match(quot;/:controller(/:action(/:id))(.:format)quot;).
    to(params, &block).name(:default)
end
Resource-ful Routes
Merb::Router.prepare do
  # Resource-ful Routes
  resources :articles
end
                      /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
Nested Routes
resources :articles
  resources :comments
end


Generating
link_to quot;Article Commentsquot;, url(:article_comments, 1)

# => /articles/1/comments
Multiple Nested Routes
 resources :articles do
   resources :comments
 end

 resources :songs do
   resources :comments
 end

 resources :photos do
   resources :comments
 end
Generating the routes...
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)
Yea, right ...

link_to quot;View Commentquot;, resource(comment.commentable, comment)

Much cleaner ...
More Resource examples
resource(@user)
            vs.
           url(:user, user)

resource(@user, :comments)
            vs.
           url(:user_comments, user)

resource(@user, @comment)
            vs.
           url(:user_comment, user, comment)
Friendly URLs
Route
resources :users, :identify => :name



Generating
resource(@user) # => /users/bryan
Can also use a block
identify(Article=>:permalink, User=>:login) do
  resources :users do
    resources :articles
  end
end


Generating
resource(@user, @article)
  # => /users/bryan/articles/hello-world
Redirecting legacy URLs
Legacy URL
/articles/123-hello-world


New URL
/articles/hello-world
In the Controller?
match(quot;/articles/:idquot;).
  to(:controller => quot;articlesquot;, :action => quot;showquot;)
Use regex to match?
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
Checking authentication
match(quot;/secretquot;).defer_to do |request, params|
  if request.session.authenticated?
    params
  end
end
Thanks!
Thanks!

More Related Content

What's hot

Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rob
 
Functional testing with capybara
Functional testing with capybaraFunctional testing with capybara
Functional testing with capybarakoffeinfrei
 
Alice Cohen - Ecotourism Green Mondays 12-12-11
Alice Cohen - Ecotourism Green Mondays 12-12-11Alice Cohen - Ecotourism Green Mondays 12-12-11
Alice Cohen - Ecotourism Green Mondays 12-12-11blueridgesustainability
 
Embracing Capybara
Embracing CapybaraEmbracing Capybara
Embracing CapybaraTim Moore
 
DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010
DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010
DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010Foil Magazine
 
Colección Primavera de Blaubloom
Colección Primavera de BlaubloomColección Primavera de Blaubloom
Colección Primavera de BlaubloomMASmedia
 
jQuery - Doing it right
jQuery - Doing it rightjQuery - Doing it right
jQuery - Doing it rightgirish82
 
Integration Test With Cucumber And Webrat
Integration Test With Cucumber And WebratIntegration Test With Cucumber And Webrat
Integration Test With Cucumber And WebratKang-min Liu
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Keyguesta2b31d
 
Confined Space Entry In Construction
Confined Space Entry In Construction Confined Space Entry In Construction
Confined Space Entry In Construction Nguyễn Quốc
 
MGREFERENCE_EJS_RO
MGREFERENCE_EJS_ROMGREFERENCE_EJS_RO
MGREFERENCE_EJS_ROChristian L
 
OIF040 HR & Social Media
OIF040 HR & Social MediaOIF040 HR & Social Media
OIF040 HR & Social MediaDiana Russo
 
Evolution of API With Blogging
Evolution of API With BloggingEvolution of API With Blogging
Evolution of API With BloggingTakatsugu Shigeta
 
Symfony und Ember.js auf einer Seite #codetalks14
Symfony und Ember.js auf einer Seite #codetalks14Symfony und Ember.js auf einer Seite #codetalks14
Symfony und Ember.js auf einer Seite #codetalks14Paul Seiffert
 

What's hot (20)

Thairuralnet
ThairuralnetThairuralnet
Thairuralnet
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008
 
Functional testing with capybara
Functional testing with capybaraFunctional testing with capybara
Functional testing with capybara
 
Alice Cohen - Ecotourism Green Mondays 12-12-11
Alice Cohen - Ecotourism Green Mondays 12-12-11Alice Cohen - Ecotourism Green Mondays 12-12-11
Alice Cohen - Ecotourism Green Mondays 12-12-11
 
Embracing Capybara
Embracing CapybaraEmbracing Capybara
Embracing Capybara
 
Abstract Shambix Giovani & Impresa
Abstract Shambix Giovani & ImpresaAbstract Shambix Giovani & Impresa
Abstract Shambix Giovani & Impresa
 
DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010
DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010
DIGITAL PHOTOGRAPHY Bloomfield College Spring 2010
 
Rails 101
Rails 101Rails 101
Rails 101
 
Colección Primavera de Blaubloom
Colección Primavera de BlaubloomColección Primavera de Blaubloom
Colección Primavera de Blaubloom
 
jQuery - Doing it right
jQuery - Doing it rightjQuery - Doing it right
jQuery - Doing it right
 
Integration Test With Cucumber And Webrat
Integration Test With Cucumber And WebratIntegration Test With Cucumber And Webrat
Integration Test With Cucumber And Webrat
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Key
 
Confined Space Entry In Construction
Confined Space Entry In Construction Confined Space Entry In Construction
Confined Space Entry In Construction
 
MGREFERENCE_EJS_RO
MGREFERENCE_EJS_ROMGREFERENCE_EJS_RO
MGREFERENCE_EJS_RO
 
OIF040 HR & Social Media
OIF040 HR & Social MediaOIF040 HR & Social Media
OIF040 HR & Social Media
 
Bangla html
Bangla htmlBangla html
Bangla html
 
Evolution of API With Blogging
Evolution of API With BloggingEvolution of API With Blogging
Evolution of API With Blogging
 
Html bangla
Html banglaHtml bangla
Html bangla
 
Joystick xkba1233 ca
Joystick xkba1233 caJoystick xkba1233 ca
Joystick xkba1233 ca
 
Symfony und Ember.js auf einer Seite #codetalks14
Symfony und Ember.js auf einer Seite #codetalks14Symfony und Ember.js auf einer Seite #codetalks14
Symfony und Ember.js auf einer Seite #codetalks14
 

Viewers also liked

Gabegie Jc
Gabegie JcGabegie Jc
Gabegie Jcpouco2
 
"We Believe" session 2
"We Believe" session 2"We Believe" session 2
"We Believe" session 2pastorjudd
 
Lesson 1 perfume intro and background
Lesson 1 perfume intro and backgroundLesson 1 perfume intro and background
Lesson 1 perfume intro and backgrounds_rodgers
 
61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf
61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf
61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdflongdanie
 
포털 뉴스 서비스와 언론사의 모바일 대응 전략
포털 뉴스 서비스와 언론사의 모바일 대응 전략포털 뉴스 서비스와 언론사의 모바일 대응 전략
포털 뉴스 서비스와 언론사의 모바일 대응 전략Sungkyu Lee
 

Viewers also liked (7)

Taipei Summary
Taipei SummaryTaipei Summary
Taipei Summary
 
Gabegie Jc
Gabegie JcGabegie Jc
Gabegie Jc
 
"We Believe" session 2
"We Believe" session 2"We Believe" session 2
"We Believe" session 2
 
Lesson 1 perfume intro and background
Lesson 1 perfume intro and backgroundLesson 1 perfume intro and background
Lesson 1 perfume intro and background
 
61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf
61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf
61-电子管收音机简明修理技术[15097.81][赵胜祥编著][青海人民出版社][1984年2月][105页][广播爱好者论坛foxhw整理制作].pdf
 
포털 뉴스 서비스와 언론사의 모바일 대응 전략
포털 뉴스 서비스와 언론사의 모바일 대응 전략포털 뉴스 서비스와 언론사의 모바일 대응 전략
포털 뉴스 서비스와 언론사의 모바일 대응 전략
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Similar to In-Depth Guide to the Merb Router

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 2009bturnbull
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編Masakuni Kato
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Adventurous Merb
Adventurous MerbAdventurous Merb
Adventurous MerbMatt Todd
 
Modware next generation with pub module
Modware next generation with pub moduleModware next generation with pub module
Modware next generation with pub modulecybersiddhu
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecordMark Menard
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On RailsWen-Tien Chang
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuLucas Renan
 
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
 
Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018wreckoning
 

Similar to In-Depth Guide to the Merb Router (20)

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
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Adventurous Merb
Adventurous MerbAdventurous Merb
Adventurous Merb
 
Modware next generation with pub module
Modware next generation with pub moduleModware next generation with pub module
Modware next generation with pub module
 
mashraqi_farhan
mashraqi_farhanmashraqi_farhan
mashraqi_farhan
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
Routing
RoutingRouting
Routing
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecord
 
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
 
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
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
 
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)
 
Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

In-Depth Guide to the Merb Router

  • 1.
  • 2. Bryan Ray http://bryanray.net
  • 3. The Merb Router In Depth ... Code Repository https://github.com/merbday/atlanta http://github.com/merbday/atlanta/tree/master/router
  • 4. Thanks Carl Lerche Anyone else who has contributed to Merb ...
  • 5. Simple Routes Merb::Router.prepare do # resources :articles # RESTful routes # resources :posts end
  • 6. Match 3 simple route Merb::Router.prepare do match(quot;/signupquot;). to(:controller => quot;usersquot;, :action => quot;newquot;). name(:signup) end Generating the route: url(:signup) => /signup
  • 7. Routes with variables Merb::Router.prepare do match(quot;/articles/:year/:month/:day/:titlequot;). to(:controller => quot;articlesquot;, :action => quot;showquot;). name(:article) end
  • 8. Routes with variables Generating url(:article, :year => 2008, :month => 07, :day => 22, :title => quot;Awesomenessquot;) # => /articles/2008/07/22/Awesomeness
  • 9. Optional Path Segments match('/articles(/:year(/:month(/:day)))/:title'). to( :controller => :articles, :action => quot;with_optional_segmentsquot;). name(:articles) /articles/hello # => { :title => “hello” } /articles/2008/12/hello # => { :title => “hello”, :year => “2008”, :month => “12” }
  • 10. Routes with conditions match(quot;/articlesquot;) do with(:controller => quot;articlesquot;) do match(quot;/:titlequot;, :title => /[a-z]+$/). to(:action => quot;with_titlequot;) match(quot;/:idquot;, :id => /^[d]+$/).to(:action => quot;with_idquot;) end end /articles/hello # => Renders the #with_title action /articles/12 # => Renders the #with_id action
  • 11. The Subdomain Problem The end goal http://<account>.localhost:4000 http://bryan.localhost:4000 Matching inside the router match(:account => 'bryan'). to(:controller => 'articles', :action => 'with_account')
  • 12. The Subdomain Problem module Merb class Request def account subdomains(0).first end end end
  • 13. #url generation ... url(:articles, :title => 'hello') # => /articles/hello url(:articles, :year => 2008, :title => 'hello') # => /articles/2008/hello url(:articles, :year => 2008, :month => 12, :title => 'hello') # => /articles/2008/12/hello url(:articles, :year => 2008, :month => 12, :day => 07, :title => 'hello') # => /articles/2008/12/7/hello # Anonymous Parameters url(:articles, 2008, 12, 07, :title => 'hello') # => /articles/2008/12/7/testing
  • 14. Default Routes def default_routes(params = {}, &block) match(quot;/:controller(/:action(/:id))(.:format)quot;). to(params, &block).name(:default) end
  • 15. Resource-ful Routes Merb::Router.prepare do # Resource-ful Routes resources :articles end /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. Nested Routes resources :articles resources :comments end Generating link_to quot;Article Commentsquot;, url(:article_comments, 1) # => /articles/1/comments
  • 17. Multiple Nested Routes resources :articles do resources :comments end resources :songs do resources :comments end resources :photos do resources :comments end
  • 18. Generating the routes... 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)
  • 19. Yea, right ... link_to quot;View Commentquot;, resource(comment.commentable, comment) Much cleaner ...
  • 20. More Resource examples resource(@user) vs. url(:user, user) resource(@user, :comments) vs. url(:user_comments, user) resource(@user, @comment) vs. url(:user_comment, user, comment)
  • 21. Friendly URLs Route resources :users, :identify => :name Generating resource(@user) # => /users/bryan
  • 22. Can also use a block identify(Article=>:permalink, User=>:login) do resources :users do resources :articles end end Generating resource(@user, @article) # => /users/bryan/articles/hello-world
  • 23. Redirecting legacy URLs Legacy URL /articles/123-hello-world New URL /articles/hello-world
  • 24. In the Controller? match(quot;/articles/:idquot;). to(:controller => quot;articlesquot;, :action => quot;showquot;)
  • 25. Use regex to match? match(quot;/articles/:idquot;, :id => /^d+-/). to(:controller => quot;articlesquot;, :action => quot;legacyquot;) match(quot;/articles/:urlquot;). to(:controller => quot;articlesquot;, :action => quot;showquot;)
  • 26. 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
  • 27. Checking authentication match(quot;/secretquot;).defer_to do |request, params| if request.session.authenticated? params end end