routes_for_blog.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. require 'rubygems'
  10. require 'action_controller'
  11. ActionController::Routing.use_controllers! [ "article", "blog" ]
  12. rs = ActionController::Routing::Routes
  13. app = ActionDispatch::Integration::Session.new(nil)
  14. ActionController::Routing::Routes.draw do |map|
  15. # Straight 'http://my.app/blog/' displays the index
  16. map.connect "blog/",
  17. :controller => "blog",
  18. :action => "index"
  19. # Return articles for a year, year/month, or year/month/day
  20. map.connect "blog/:year/:month/:day",
  21. :controller => "blog",
  22. :action => "show_date",
  23. :requirements => { :year => /(19|20)\d\d/,
  24. :month => /[01]?\d/,
  25. :day => /[0-3]?\d/},
  26. :day => nil,
  27. :month => nil
  28. # Show an article identified by an id
  29. map.connect "blog/show/:id",
  30. :controller => "blog",
  31. :action => "show",
  32. :id => /\d+/
  33. # Regular Rails routing for admin stuff
  34. map.connect "blog/:controller/:action/:id"
  35. # Catchall so we can gracefully handle badly formed requests
  36. map.connect "*anything",
  37. :controller => "blog",
  38. :action => "unknown_request"
  39. end
  40. rs.recognize_path "/blog"
  41. rs.recognize_path "/blog/show/123"
  42. rs.recognize_path "/blog/2004"
  43. rs.recognize_path "/blog/2004/12"
  44. rs.recognize_path "/blog/2004/12/25"
  45. rs.recognize_path "/blog/article/edit/123"
  46. rs.recognize_path "/blog/article/show_stats"
  47. rs.recognize_path "/blog/wibble"
  48. rs.recognize_path "/junk"
  49. last_request = rs.recognize_path "/blog/2006/07/28"
  50. rs.generate({:day => 25}, last_request)
  51. rs.generate({:year => 2005}, last_request)
  52. rs.generate({:action => "show" , :id => 123}, last_request)
  53. rs.generate({:year => 2006}, last_request)
  54. rs.generate({:year => 2006, :month => nil}, last_request)
  55. app.url_for :controller => 'blog', :action => 'show_date', :year => 2002
  56. app.url_for :controller => 'blog', :action => 'show_date', :overwrite_params => {:year => "2002" }