SHARE
TWEET

Untitled

a guest Jul 24th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Router
  2.   Route = Struct.new(:pattern, :block)
  3.  
  4.   class RouteSet
  5.     def on(pattern, &block)
  6.       Router.routes.push Route.new(pattern, block)
  7.     end
  8.   end
  9.  
  10.   @routes = []
  11.  
  12.   def self.routes
  13.     @routes
  14.   end
  15.  
  16.   def self.define(&block)
  17.     route_set = RouteSet.new
  18.     route_set.instance_eval(&block)
  19.   end
  20.  
  21.   def self.run(path)
  22.     params = {}
  23.  
  24.     matched_route = routes.find do |route|
  25.       matched = path.match /\A#{route.pattern}\z/i
  26.       params = matched.named_captures if matched
  27.       !!matched
  28.     end
  29.  
  30.     matched_route.block.call(params) if matched_route
  31.   end
  32. end
  33.  
  34. Router.define do
  35.   on 'patterm' do
  36.     # do something, return response
  37.   end
  38. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top