Instantiate validators at definition time#2657
Draft
ericproulx wants to merge 1 commit intomasterfrom
Draft
Conversation
Danger ReportNo issues found. |
5d145a5 to
f87920f
Compare
Contributor
Author
|
Missing UPGRADING notes. Working on it |
2ecb403 to
cf04c9d
Compare
Member
|
Is there a tradeoff with things like |
Contributor
Author
7a04c46 to
a0c19b8
Compare
- Store validator instances in ParamsScope/ContractScope and have
Endpoint#run_validators read them directly
- Remove ValidatorFactory indirection and eagerly compute validator
messages/options in constructors
- Extract Grape::Util::Translation module shared by Exceptions::Base
and Validators::Base for I18n translate with fallback locale
- Support Hash messages in translate_message for deferred translation
with interpolation parameters (e.g. { key: :length, min: 2 })
- Normalize Grape::Exceptions::Validation params handling and refactor
validator specs to define routes per example group
- Drop test-prof dependency and its spec config
Co-authored-by: Cursor <cursoragent@cursor.com>
a0c19b8 to
c1722bb
Compare
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.
Instantiate validators at definition time
Summary
Validators are now instantiated at definition time (in
ParamsScopeandContractScope) rather than at request time viaValidatorFactory. This eliminates per-request object allocation overhead and allows expensive setup (option parsing, converter building) to happen once.I18n translation is handled through a shared
Grape::Util::Translationmodule. Validators that need interpolation parameters (e.g.LengthValidator,SameAsValidator) store a Hash{ key: :length, min: 2, max: 5 }as their message.Exceptions::Base#translate_messagedispatches on type — Symbol, Hash, Proc, or String — so translation with the correct locale always happens at error-raise time.Changes
Shared translation module (
Grape::Util::Translation)translate(with fallback locale logic) intoGrape::Util::Translation, included by bothExceptions::BaseandValidators::BaseFALLBACK_LOCALE,translate, andfallback_messagefromExceptions::BaseExceptions::Base#translate_messageandtranslate_attributesdelegate totranslatewith ascope:parameterExceptions::Base#translate_messagenow supports Hash messages:{ key: :symbol, **interpolation_params }for deferred translation with interpolationValidators::Base#translate_messagedelegates totranslatewith thegrape.errors.messagesscopeCore architecture
ParamsScope#validateandContractScopenow store validator instances instead of option hashes innamespace_stackable[:validations]ParamsScope#coerce_typereceivesvalidations.extract!(:coerce, :coerce_with, :coerce_message)instead of the full hash, replacing the individualdeletecalls that followedEndpoint#run_validatorstakes arequest:keyword arg, reads validators directly frominheritable_setting.route[:saved_validations], and short-circuits withreturn if validators.blank?Endpoint#validationsenumerator methodValidatorFactoryValidator base (
Validators::Base)fail_fast?is now an explicit public methodvalidate!,message,options_key?to privateoptions_key?simplified to a singlekeyparameterhash_like?,option_value,scrub,translate_messagemessageaccepts a block for lazy default generation, returnskeywhen present@fail_fast, @allow_blank = opts.values_at(:fail_fast, :allow_blank)in constructorValidator optimizations — eagerly compute in
initializeAllowBlankValidator: caches@valueand@exception_message; useshash_like?andscrubCoerceValidator: resolves type and builds converter; caches@exception_message; inlinesvalid_type?check; removestype,converter,valid_type?DefaultValidator: pre-builds@default_calllambda; removesvalidate_param!, inlines intovalidate!ExceptValuesValidator: validates proc arity; pre-builds@excepts_calllambda; caches@exception_messageLengthValidator: validates arguments; stores a Hash message ({ key: :length, min:, max: }) for deferred i18n translation with interpolationValuesValidator: validates proc arity; pre-builds@values_calllambda; caches@exception_messageRegexpValidator: caches@valueand@exception_message; usesBase#scrubSameAsValidator: caches@value; stores a Hash message ({ key: :same_as, parameter: }) for deferred i18n translation with interpolationPresenceValidator: caches@exception_messageAllOrNoneOfValidator,MutuallyExclusiveValidator: cache@exception_messageAtLeastOneOfValidator: caches@exception_message; inverts guard toreturn if keys_in_common(params).any?ExactlyOneOfValidator: caches@exactly_one_exception_messageand@mutual_exclusion_exception_messageContractScopeValidator: no longer inherits fromBase; standalone class with(schema:)constructor and its ownfail_fast?params:argument simplificationGrape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)])simplified toparams: @scope.full_name(attr_name)throughout, sinceValidationnow coerces to array internallyattr_accessor :params, :message_keychanged toattr_readerSpecs
let_it_be(:app)with per-describelet(:app)blocks so each test group defines only the route(s) it needsendpoint_run_validators.grapenotification expectations for empty-validator casesLengthValidatorandSameAsValidatorconfirming request-time locale is used regardless of definition-time localeRemoved
test-profdependencytest-profgem fromGemfilespec/config/spec_test_prof.rbconfigfrom the spec helper directory loaderTest plan
bundle exec rspec)