Prioritize env API_FORMAT over Rack::CONTENT_TYPE header #2505
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
As per #2171
Fix the Order of Conditions in
fetch_formatter
to Correctly Use Custom FormattersIssue:
In
Grape::Middleware::Formatter.fetch_formatter
, the current order of conditions causes custom formatters specified inenv[Grape::Env::API_FORMAT]
to be ignored in favor of the default formatter associated with theContent-Type
header.Original Code:
Problem:
This code prioritizes the
Content-Type
header over theenv[Grape::Env::API_FORMAT]
. As a result, even if a custom formatter is explicitly set in the environment, it may be overridden by the default formatter determined by theContent-Type
.Solution:
Swap the order of conditions so that
env[Grape::Env::API_FORMAT]
takes precedence:Rationale:
By giving priority to
env[Grape::Env::API_FORMAT]
, we ensure that custom formatters are correctly recognized and applied, allowing for more flexible and accurate response formatting.Example:
Before the Fix:
The custom formatter
:raw_json
is not applied. Instead, Grape uses its default JSON formatter.After the Fix:
The custom formatter
:raw_json
is correctly applied, and the response body is returned exactly as intended.