Fix middleware build crash when a top-level ::Options constant is in scope#2773
Merged
Merged
Conversation
1bac8b4 to
cb4b958
Compare
Danger ReportNo issues found. |
Grape::Middleware::Base#initialize used self.class.const_defined?(:Options), whose default inherit: true reaches top-level constants on Object. When any loaded gem defines a global ::Options (e.g. the `options` gem, a transitive dependency of progress_bar), the guard returned true for every middleware subclass, but `self.class::Options` then raised NameError because the `::` resolution operator does not fall back to Object. This took down the whole middleware stack for third-party middleware that does not declare its own Options (e.g. grape_logging's RequestLogger). Resolve the constant through self.class::Options directly: `::` already honours middleware inheritance (e.g. Versioner::Path -> Versioner::Base) and never falls back to Object, so a global ::Options is no longer matched and an absent one cleanly yields the legacy DEFAULT_OPTIONS path. Apply the same treatment to the DEFAULT_OPTIONS lookup, which had the identical defect. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
cb4b958 to
47271c8
Compare
dblock
approved these changes
Jun 29, 2026
dblock
reviewed
Jun 29, 2026
| # → Versioner::Base) and, unlike const_defined?, never resolves a | ||
| # top-level ::Options on Object. Absent an own/inherited Options class, | ||
| # the lookup raises NameError and we fall back to the legacy path. | ||
| def options_data_class |
Member
There was a problem hiding this comment.
Does it make sense to expose these as methods? Do they need to be private?
Contributor
Author
There was a problem hiding this comment.
They're already private — defined below the private on line 80, which sits just above this hunk so it doesn't show in the diff view (private_method_defined? confirms it for both).
Each is used exactly once (options_data_class in #initialize, default_options_constant in #merge_default_options). They're extracted only to scope rescue NameError to the constant lookup itself:
- the inline
rescuemodifier (self.class::Options rescue nil) would swallow everyStandardError, not justNameError, and tripsStyle/RescueModifier; - a single parametric helper isn't possible here since
::is literal-only, and its dynamic equivalentconst_getreintroduces the top-level::Options-on-Objectfallback this PR is removing.
Happy to inline them into begin/rescue blocks if you'd prefer fewer methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Fixes #2772.
Problem
Since 3.3.0,
Grape::Middleware::Base#initializeroutes options through a per-classOptionsDatavalue object when the subclass declares one:const_defined?(:Options)defaults toinherit: true, so the lookup also walks up to top-level constants onObject. If anything in the process defines a global::Options, the guard returnstruefor every middleware subclass — even ones that never declare their ownOptions. The subsequentself.class::Optionsthen raisesNameError, because the::resolution operator does not fall back toObject. The whole middleware stack fails to build.This is not hypothetical: the
optionsgem defines a top-level::Optionsmodule on load and is a transitive dependency of common gems (e.g.progress_bar). With it loaded, every third-party middleware that subclassesGrape::Middleware::Basewithout its ownOptions(e.g.grape_logging'sRequestLogger) crashes:The
DEFAULT_OPTIONSpath inmerge_default_optionshad the identical defect (self.class.const_defined?(:DEFAULT_OPTIONS)→self.class::DEFAULT_OPTIONS), so a global::DEFAULT_OPTIONSwould crash the same way.Fix
Drop the
const_defined?guard entirely and resolve throughself.class::Optionsdirectly:The
::resolution operator already does exactly what we need: it honours middleware inheritance (e.g.Versioner::Path→Versioner::Base) and, unlikeconst_defined?, it never falls back to a top-level::OptionsonObject. So a global::Optionsis no longer matched, and a middleware that declares none cleanly yields the legacyDEFAULT_OPTIONSpath. The same treatment is applied to theDEFAULT_OPTIONSlookup.This came down to a quirk of Ruby's reflection API: no predicate method matches the
::operator's "inherit through ancestors but skipObject" semantics —const_defined?(:X)/const_get(:X)includeObject(the bug), while theirinherit: falseforms drop inheritance (which would breakVersioner::Path). Letting::raise and rescuing is the most direct way to mirror its behaviour.Tests
Added regression specs to
spec/grape/middleware/base_spec.rb(usingstub_constfor the global constant, auto-cleaned per example):Optionsbuilds and takes the legacyDEFAULT_OPTIONSpath even with a global::Optionsin scope (the crash repro), and exposes noconfig.::DEFAULT_OPTIONSis ignored by the legacy merge path.Optionsstill routes through it, including when a global::Optionsis present.OptionsDataclass without redeclaring it.Benchmark
#initializeruns once per middleware at app-build time, not per request (calldoesdup.call!, which doesn't re-runinitialize), so this is a boot-path concern only. Comparing the::-and-rescue approach against the alternative (walkingself.class.ancestorswithconst_defined?(name, false)), measured on Ruby 4.0.5 withbenchmark-ips:::+ rescueOptions(Formatter,Error,Versioner::Base)Options(Versioner::Path)Options(most third-party middleware)::-and-rescue is faster in exactly the shapes Grape ships (everything internal declares or inheritsOptions); it is slower only for no-Optionsmiddleware, where it pays theNameErrorcost — and that ~250 ns delta is boot-only and dwarfed by the rest of construction (a fullThirdParty.newwith noOptionsis ~1.33 µs, still faster thanFormatter.newat ~2.02 µs).Verification
bundle exec rspec spec/grape/middleware/— all green.bundle exec rubocop lib/grape/middleware/base.rb spec/grape/middleware/base_spec.rb— no offenses.🤖 Generated with Claude Code