lib/grape/middleware/versioner/accept_version_header.rb in grape-2.1.3 vs lib/grape/middleware/versioner/accept_version_header.rb in grape-2.2.0

- old
+ new

@@ -15,48 +15,25 @@ # # If version does not match this route, then a 406 is raised with # X-Cascade header to alert Grape::Router to attempt the next matched # route. class AcceptVersionHeader < Base + include VersionerHelpers + def before - potential_version = (env[Grape::Http::Headers::HTTP_ACCEPT_VERSION] || '').strip + potential_version = env[Grape::Http::Headers::HTTP_ACCEPT_VERSION]&.strip + not_acceptable!('Accept-Version header must be set.') if strict? && potential_version.blank? - if strict? && potential_version.empty? - # If no Accept-Version header: - throw :error, status: 406, headers: error_headers, message: 'Accept-Version header must be set.' - end + return if potential_version.blank? - return if potential_version.empty? - - # If the requested version is not supported: - throw :error, status: 406, headers: error_headers, message: 'The requested version is not supported.' unless versions.any? { |v| v.to_s == potential_version } - + not_acceptable!('The requested version is not supported.') unless potential_version_match?(potential_version) env[Grape::Env::API_VERSION] = potential_version end private - def versions - options[:versions] || [] - end - - def strict? - options[:version_options] && options[:version_options][:strict] - end - - # By default those errors contain an `X-Cascade` header set to `pass`, which allows nesting and stacking - # of routes (see Grape::Router) for more information). To prevent - # this behavior, and not add the `X-Cascade` header, one can set the `:cascade` option to `false`. - def cascade? - if options[:version_options]&.key?(:cascade) - options[:version_options][:cascade] - else - true - end - end - - def error_headers - cascade? ? { Grape::Http::Headers::X_CASCADE => 'pass' } : {} + def not_acceptable!(message) + throw :error, status: 406, headers: error_headers, message: message end end end end end