Simple Ruby router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Router | |
Route = Struct.new(:pattern, :block) | |
class RouteSet | |
def on(pattern, &block) | |
Router.routes.push Route.new(pattern, block) | |
end | |
end | |
@routes = [] | |
def self.routes | |
@routes | |
end | |
def self.define(&block) | |
route_set = RouteSet.new | |
route_set.instance_eval(&block) | |
end | |
def self.run(path) | |
params = {} | |
matched_route = routes.find do |route| | |
matched = path.match /\A#{route.pattern}\z/i | |
params = matched.named_captures if matched | |
!!matched | |
end | |
matched_route.block.call(params) if matched_route | |
end | |
end | |
Router.define do | |
on 'pattern' do | |
# do something, return response | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment