Skip to content

Commit

Permalink
ContractScope's validator inherits from Grape::Validations::Validator…
Browse files Browse the repository at this point in the history
…::Base

initialize method has been updated accordingly
opts adds fail_fast
Use << when concatenating string
Use map instead of each []
  • Loading branch information
ericproulx committed Oct 27, 2024
1 parent 139e96b commit 23ab494
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions lib/grape/validations/contract_scope.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,18 @@ def initialize(api, contract = nil, &block)

validator_options = {
validator_class: Validator,
opts: { schema: contract }
opts: { schema: contract, fail_fast: false }
}

api.namespace_stackable(:validations, validator_options)
end

class Validator
class Validator < Grape::Validations::Validators::Base
attr_reader :schema

def initialize(*_args, schema:)
@schema = schema
def initialize(_attrs, _options, _required, _scope, opts)
super
@schema = opts.fetch(:schema)
end

# Validates a given request.
Expand All @@ -49,21 +50,17 @@ def validate(request)
return
end

errors = []

res.errors.messages.each do |message|
full_name = message.path.first.to_s
raise Grape::Exceptions::ValidationArrayErrors.new(build_errors_from_messages(res.errors.messages))
end

full_name += "[#{message.path[1..].join('][')}]" if message.path.size > 1
private

errors << Grape::Exceptions::Validation.new(params: [full_name], message: message.text)
def build_errors_from_messages(messages)
messages.map do |message|
full_name = message.path.first.to_s
full_name << "[#{message.path[1..].join('][')}]" if message.path.size > 1
Grape::Exceptions::Validation.new(params: [full_name], message: message.text)
end

raise Grape::Exceptions::ValidationArrayErrors.new(errors)
end

def fail_fast?
false
end
end
end
Expand Down

0 comments on commit 23ab494

Please sign in to comment.