routes.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. module Journey
  2. ###
  3. # The Routing table. Contains all routes for a system. Routes can be
  4. # added to the table by calling Routes#add_route
  5. class Routes
  6. include Enumerable
  7. attr_reader :routes, :named_routes
  8. def initialize
  9. @routes = []
  10. @named_routes = {}
  11. @ast = nil
  12. @partitioned_routes = nil
  13. @simulator = nil
  14. end
  15. def length
  16. @routes.length
  17. end
  18. alias :size :length
  19. def last
  20. @routes.last
  21. end
  22. def each(&block)
  23. routes.each(&block)
  24. end
  25. def clear
  26. routes.clear
  27. end
  28. def partitioned_routes
  29. @partitioned_routes ||= routes.partition { |r|
  30. r.path.anchored && r.ast.grep(Nodes::Symbol).all? { |n| n.default_regexp? }
  31. }
  32. end
  33. def ast
  34. return @ast if @ast
  35. return if partitioned_routes.first.empty?
  36. asts = partitioned_routes.first.map { |r| r.ast }
  37. @ast = Nodes::Or.new(asts)
  38. end
  39. def simulator
  40. return @simulator if @simulator
  41. gtg = GTG::Builder.new(ast).transition_table
  42. @simulator = GTG::Simulator.new gtg
  43. end
  44. ###
  45. # Add a route to the routing table.
  46. def add_route app, path, conditions, defaults, name = nil
  47. route = Route.new(name, app, path, conditions, defaults)
  48. route.precedence = routes.length
  49. routes << route
  50. named_routes[name] = route if name
  51. clear_cache!
  52. route
  53. end
  54. private
  55. def clear_cache!
  56. @ast = nil
  57. @partitioned_routes = nil
  58. @simulator = nil
  59. end
  60. end
  61. end