From 707b00b91b26b250322299ef9250ef4c98cf2e1d Mon Sep 17 00:00:00 2001 From: Eric Proulx Date: Tue, 11 Jun 2024 01:33:41 +0200 Subject: [PATCH] Use `route.namespace` instead instance_variable_get(@options) (#931) Rename `route_instance_variable_equals?` to `route_namespace_equals?` Refactor route_path_start_with? and route_namespace_equals? with Enumerator instead of static Arrays Refactor determine_namespaced_routes in positive logic (select over reject) --- lib/grape-swagger.rb | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/lib/grape-swagger.rb b/lib/grape-swagger.rb index c88511f1..76474a19 100644 --- a/lib/grape-swagger.rb +++ b/lib/grape-swagger.rb @@ -45,12 +45,10 @@ def combine_routes(app, doc_klass) end def determine_namespaced_routes(name, parent_route, routes) - if parent_route.nil? - routes.values.flatten - else - parent_route.reject do |route| - !route_path_start_with?(route, name) || !route_instance_variable_equals?(route, name) - end + return routes.values.flatten if parent_route.nil? + + parent_route.select do |route| + route_path_start_with?(route, name) || route_namespace_equals?(route, name) end end @@ -94,20 +92,27 @@ def extract_parent_route(name) matches.nil? ? route_name : matches[0].delete('/') end - def route_instance_variable(route) - route.instance_variable_get(:@options)[:namespace] - end + def route_namespace_equals?(route, name) + patterns = Enumerator.new do |yielder| + yielder << "/#{name}" + yielder << "/:version/#{name}" + end - def route_instance_variable_equals?(route, name) - route_instance_variable(route) == "/#{name}" || - route_instance_variable(route) == "/:version/#{name}" + patterns.any? { |p| route.namespace == p } end def route_path_start_with?(route, name) - route_prefix = route.prefix ? "/#{route.prefix}/#{name}" : "/#{name}" - route_versioned_prefix = route.prefix ? "/#{route.prefix}/:version/#{name}" : "/:version/#{name}" + patterns = Enumerator.new do |yielder| + if route.prefix + yielder << "/#{route.prefix}/#{name}" + yielder << "/#{route.prefix}/:version/#{name}" + else + yielder << "/#{name}" + yielder << "/:version/#{name}" + end + end - route.path.start_with?(route_prefix, route_versioned_prefix) + patterns.any? { |p| route.path.start_with?(p) } end end