Skip to content

Instantly share code, notes, and snippets.

@sobstel sobstel/router.rb
Last active Aug 21, 2019

Embed
What would you like to do?
Simple Ruby router
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
You can’t perform that action at this time.