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 committed Nov 15, 2015
1 parent a9a29a4 commit fa6b90d
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

* Your contribution here.

* [#1203](https://github.com/ruby-grape/grape/pull/1203): Allow custom coercion failure messages - [@zuk](https://github.com/zuk).
* [#1196](https://github.com/ruby-grape/grape/pull/1196): Allow multiple `before_each` blocks - [@huynhquancam](https://github.com/huynhquancam).
* [#1190](https://github.com/ruby-grape/grape/putt/1190): Bypass formatting for statuses with no entity-body - [@tylerdooling](https://github.com/tylerdooling).
* [#1188](https://github.com/ruby-grape/grape/putt/1188): Allow parameters with more than one type - [@dslh](https://github.com/dslh).
Expand Down
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ desc 'Returns your public timeline.' do
description: 'Not really needed',
required: false
}

end
get :public_timeline do
Status.limit(20)
Expand Down Expand Up @@ -751,7 +751,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 @@ -761,8 +763,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
7 changes: 6 additions & 1 deletion lib/grape/validations/validators/coerce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ def validate_param!(attr_name, params)
if valid_type?(new_value)
params[attr_name] = new_value
else
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message_key: :coerce
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

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 @@ -118,6 +118,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 fa6b90d

Please sign in to comment.