Skip to content

Resolve custom validators from API namespace (#1178)#2658

Open
GulfGulfinson wants to merge 2 commits intoruby-grape:masterfrom
GulfGulfinson:custom-validator-namespace-lookup
Open

Resolve custom validators from API namespace (#1178)#2658
GulfGulfinson wants to merge 2 commits intoruby-grape:masterfrom
GulfGulfinson:custom-validator-namespace-lookup

Conversation

@GulfGulfinson
Copy link

Fixes #1178

What

Custom validators (e.g. 'uuid: true') are resolved from the apis namespace, when they are not in the global registry. For example for an api under Api::V2::Jobs, Grape looks up 'Api::V2::Validators::Uuid' when it sees uuid: truein params, so you no longer need to requirethe validator file yourself.

Why

Previosly using a namespaced custom validator (e.g. 'Api::V2::Validators::Uuid) required manually requiring the file in the API (e.g. in base.rb). With Rails autoloading, that led to the file being loaded twice and already initialized constant warnings.

How

  • 'Grape::Validations.require_validator' accepts an optional 'api_class:' and, when the validator is missing from the registry, tries to find it under the API’s namespace (e.g. Api::V2::Validators::Uuid).
  • 'ParamsScope' passes the current API class (using base for remountable APIs) so lookup uses the correct namespace.
  • 'Grape::API::Instance' now has a public base reader for that resolution.

Tests added in spec/grape/api/custom_validations_spec.rb for the namespace lookup behavior.

phillschnei@web.de and others added 2 commits February 14, 2026 10:05
When a validator short name (e.g. :uuid) is not in the global registry,
Grape now looks up the constant in the API's namespace under
Validators::<Name> (e.g. Api::V2::Validators::Uuid for Api::V2::Jobs).

This fixes the require-order / double-load issue when using custom
validators in Rails: params like 'uuid: true' can resolve to a
validator class in the same API namespace without explicit require
or global Grape::Validations.register, and without triggering
'already initialized constant' warnings.

- Add optional scope: to require_validator; pass API from ParamsScope
- Add find_custom_validator_in_scope and resolve_api_class (use
  mount instance's @base for named API class when present)
- Add specs for scope-based lookup and integration with params

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@GulfGulfinson GulfGulfinson force-pushed the custom-validator-namespace-lookup branch from f1c8740 to 8bb87a3 Compare February 14, 2026 09:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Grape::Exceptions::UnknownValidator

1 participant