|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Grape |
| 4 | + class Router |
| 5 | + # Grape-style path patterns for Mustermann: `:param`, `*splat`, `{name}` / |
| 6 | + # `{+splat}`, `( )` optionals, `|`, and an Integer digit-only constraint |
| 7 | + # (driven by Grape's `params` option). |
| 8 | + # |
| 9 | + # Inlined from the mustermann-grape gem (MIT) by namusyaka, Konstantin Haase |
| 10 | + # and Daniel Doubrovkine. Grape instantiates this class directly (see |
| 11 | + # {Grape::Router::Pattern}), so unlike the gem it is not registered as a |
| 12 | + # Mustermann `type: :grape`. |
| 13 | + class MustermannPattern < ::Mustermann::AST::Pattern |
| 14 | + supported_options :params |
| 15 | + |
| 16 | + on(nil, '?', ')') { |c| unexpected(c) } |
| 17 | + |
| 18 | + on('*') { |_c| scan(/\w+/) ? node(:named_splat, buffer.matched) : node(:splat) } |
| 19 | + on(':') do |_c| |
| 20 | + param_name = scan(/\w+/) |
| 21 | + # Integer params (declared via Grape's `params` option) match digits only; |
| 22 | + # any other capture matches a single path segment (anything but / ? # .). |
| 23 | + param_type = pattern&.options&.dig(:params, param_name, :type) |
| 24 | + constraint = param_type == 'Integer' ? /\d/ : '[^/?#.]' |
| 25 | + node(:capture, param_name, constraint:) { scan(/\w+/) } |
| 26 | + end |
| 27 | + on('\\') { |_c| node(:char, expect(/./)) } |
| 28 | + on('(') { |_c| node(:optional, node(:group) { read unless scan(')') }) } |
| 29 | + on('|') { |_c| node(:or) } |
| 30 | + |
| 31 | + on('{') do |_c| |
| 32 | + type = scan('+') ? :named_splat : :capture |
| 33 | + name = expect(/[\w.]+/) |
| 34 | + type = :splat if (type == :named_splat) && (name == 'splat') |
| 35 | + expect('}') |
| 36 | + node(type, name) |
| 37 | + end |
| 38 | + |
| 39 | + suffix('?') do |_c, element| |
| 40 | + node(:optional, element) |
| 41 | + end |
| 42 | + end |
| 43 | + end |
| 44 | +end |
0 commit comments