Skip to content

Instantly share code, notes, and snippets.

@exts
Last active January 5, 2017 05:00
Show Gist options
  • Save exts/1eaa26197c0a20bd877c957e7b52ef8e to your computer and use it in GitHub Desktop.
Save exts/1eaa26197c0a20bd877c957e7b52ef8e to your computer and use it in GitHub Desktop.
Example of how to approach route containers with groups and sub groups in crystal language (inspired by php frameworks such as Slim Framework 3)
class Route
def initialize(@route = "")
end
def route
@route
end
end
class RouteContainer
@routes = [] of Route
@groups = [] of String
def routes
@routes
end
def add(route : String)
route = parse_route(route)
@routes << Route.new route
end
def group(route : String, &closure : RouteContainer ->)
@groups << route
closure.call(self)
@groups.pop?
end
private def parse_route(route : String)
# remove trailing forward slash from end of each group before joining
@groups.map!{ |g| g.chomp('/').lchomp('/') }
group_prefix = @groups.join('/').strip
route = route.lchomp('/')
route = group_prefix + "/" + route
route = "/" + route if !group_prefix.empty?
route
end
end
container = RouteContainer.new
container.group "/admin", do |router|
router.group "/users", do |router|
router.add("/update")
router.add("/edit")
end
router.group "/staff", do |router|
router.add("/promotion")
end
end
container.routes.each do |route|
puts route.route
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment