Skip to content

Instantly share code, notes, and snippets.

@sobstel
Last active November 13, 2019 12:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sobstel/65335ae07c4e709a9773ed8815a8e2e5 to your computer and use it in GitHub Desktop.
Save sobstel/65335ae07c4e709a9773ed8815a8e2e5 to your computer and use it in GitHub Desktop.
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