Skip to content

Commit

Permalink
allow custom param coercion failure messages
Browse files Browse the repository at this point in the history
Custom param types can now report why coercion failed in their .parse
method by returning an InvalidValue initialized with an error message.
For example:

  Grape::Validations::Types::InvalidValue.new "is too short"
  • Loading branch information
Matt Zukowski authored and Matt Zukowski committed Jul 2, 2016
1 parent 5936ee6 commit 242ecea
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 6 deletions.
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,9 @@ Aside from the default set of supported types listed above, any class can be
used as a type so long as an explicit coercion method is supplied. If the type
implements a class-level `parse` method, Grape will use it automatically.
This method must take one string argument and return an instance of the correct
type, or raise an exception to indicate the value was invalid. E.g.,
type. An exception raised inside the `parse` method will be reported as a validation
failure with a generic error message. To report a custom error message, return an
`InvalidValue` initialized with the custom message. E.g.,

```ruby
class Color
Expand All @@ -813,8 +815,11 @@ class Color
end

def self.parse(value)
fail 'Invalid color' unless %w(blue red green).include?(value)
new(value)
if %w(blue red green).include?(value)
new(value)
else
Grape::Validations::Types::InvalidValue.new "is not a valid color"
end
end
end

Expand Down
7 changes: 6 additions & 1 deletion lib/grape/validations/types.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ module Validations
module Types
# Instances of this class may be used as tokens to denote that
# a parameter value could not be coerced.
class InvalidValue; end
class InvalidValue
attr_reader :message
def initialize(message = nil)
@message = message
end
end

# Types representing a single value, which are coerced through Virtus
# or special logic in Grape.
Expand Down
12 changes: 10 additions & 2 deletions lib/grape/validations/validators/coerce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,16 @@ def initialize(*_args)
def validate_param!(attr_name, params)
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:coerce) unless params.is_a? Hash
new_value = coerce_value(params[attr_name])
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:coerce) unless valid_type?(new_value)
params[attr_name] = new_value
if valid_type?(new_value)
params[attr_name] = new_value
else
bad_value = new_value
if bad_value.is_a?(Types::InvalidValue) && !bad_value.message.nil?
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: bad_value.message.to_s
else
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message_key: :coerce
end
end
end

private
Expand Down
48 changes: 48 additions & 0 deletions spec/grape/validations/params_scope_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,54 @@ def initialize(value)
expect(last_response.status).to eq(400)
expect(last_response.body).to match(/foo is invalid/)
end

context 'when the parse method returns an InvalidValue' do
module ParamsScopeSpec
class AnotherCustomType
attr_reader :value
def self.parse(value)
case value
when 'invalid with message'
Grape::Validations::Types::InvalidValue.new 'is not correct'
when 'invalid without message'
Grape::Validations::Types::InvalidValue.new
else
new(value)
end
end

def initialize(value)
@value = value
end
end
end

context 'with a message' do
it 'fails with the InvalidValue\'s error message' do
subject.params do
requires :foo, type: ParamsScopeSpec::AnotherCustomType
end
subject.get('/types') { params[:foo].value }

get '/types', foo: 'invalid with message'
expect(last_response.status).to eq(400)
expect(last_response.body).to match(/foo is not correct/)
end
end

context 'without a message' do
it 'fails with the default coercion failure message' do
subject.params do
requires :foo, type: ParamsScopeSpec::AnotherCustomType
end
subject.get('/types') { params[:foo].value }

get '/types', foo: 'invalid without message'
expect(last_response.status).to eq(400)
expect(last_response.body).to match(/foo is invalid/)
end
end
end
end

context 'array without coerce type explicitly given' do
Expand Down

0 comments on commit 242ecea

Please sign in to comment.