-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
validation / coercion support #201
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4800c93
added coercion+validation support
schmurfy 79435d6
allow passing documentation to requires/optional
schmurfy d0d7872
reworked validations
schmurfy fdd865b
Allow type or coerce to specify coercion type
schmurfy bc3318c
extracted validator tests in their own fiels
schmurfy b68b777
added validations in README
schmurfy 87b46d7
moved Boolean type definition
schmurfy 50b8dc8
rephrased mention of virtus and added link
schmurfy beb22f3
moved Boolean class definition
schmurfy 8f89489
updated README
schmurfy b5db980
added validation behind the coercion
schmurfy 908bc2d
moved coerce test service in namespace
schmurfy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
require 'virtus' | ||
|
||
module Grape | ||
|
||
module Validations | ||
|
||
## | ||
# All validators must inherit from this class. | ||
# | ||
class Validator | ||
def initialize(attrs, options) | ||
@attrs = Array(attrs) | ||
|
||
if options.is_a?(Hash) && !options.empty? | ||
raise "unknown options: #{options.keys}" | ||
end | ||
end | ||
|
||
def validate!(params) | ||
@attrs.each do |attr_name| | ||
validate_param!(attr_name, params) | ||
end | ||
end | ||
|
||
private | ||
|
||
def self.convert_to_short_name(klass) | ||
ret = klass.name.gsub(/::/, '/'). | ||
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). | ||
gsub(/([a-z\d])([A-Z])/,'\1_\2'). | ||
tr("-", "_"). | ||
downcase | ||
File.basename(ret, '_validator') | ||
end | ||
end | ||
|
||
## | ||
# Base class for all validators taking only one param. | ||
class SingleOptionValidator < Validator | ||
def initialize(attrs, options) | ||
@option = options | ||
super | ||
end | ||
|
||
end | ||
|
||
# we define Validator::inherited here so SingleOptionValidator | ||
# will not be considered a validator. | ||
class Validator | ||
def self.inherited(klass) | ||
short_name = convert_to_short_name(klass) | ||
Validations::register_validator(short_name, klass) | ||
end | ||
end | ||
|
||
|
||
|
||
class <<self | ||
attr_accessor :validators | ||
end | ||
|
||
self.validators = {} | ||
|
||
def self.register_validator(short_name, klass) | ||
validators[short_name] = klass | ||
end | ||
|
||
|
||
class ParamsScope | ||
def initialize(api, &block) | ||
@api = api | ||
instance_eval(&block) | ||
end | ||
|
||
def requires(*attrs) | ||
validations = {:presence => true} | ||
if attrs.last.is_a?(Hash) | ||
validations.merge!(attrs.pop) | ||
end | ||
|
||
validates(attrs, validations) | ||
end | ||
|
||
def optional(*attrs) | ||
validations = {} | ||
if attrs.last.is_a?(Hash) | ||
validations.merge!(attrs.pop) | ||
end | ||
|
||
validates(attrs, validations) | ||
end | ||
|
||
private | ||
def validates(attrs, validations) | ||
doc_attrs = { :required => validations.keys.include?(:presence) } | ||
|
||
# special case (type = coerce) | ||
if validations[:type] | ||
validations[:coerce] = validations.delete(:type) | ||
end | ||
|
||
if coerce_type = validations[:coerce] | ||
doc_attrs[:type] = coerce_type.to_s | ||
end | ||
|
||
if desc = validations.delete(:desc) | ||
doc_attrs[:desc] = desc | ||
end | ||
|
||
@api.document_attribute(attrs, doc_attrs) | ||
|
||
validations.each do |type, options| | ||
validator_class = Validations::validators[type.to_s] | ||
if validator_class | ||
@api.settings[:validations] << validator_class.new(attrs, options) | ||
else | ||
raise "unknown validator: #{type}" | ||
end | ||
end | ||
|
||
end | ||
|
||
end | ||
|
||
# This module is mixed into the API Class. | ||
module ClassMethods | ||
def reset_validations! | ||
settings[:validations] = [] | ||
end | ||
|
||
def params(&block) | ||
ParamsScope.new(self, &block) | ||
end | ||
|
||
def document_attribute(names, opts) | ||
if @last_description | ||
@last_description[:params] ||= {} | ||
|
||
Array(names).each do |name| | ||
@last_description[:params][name.to_sym] ||= {} | ||
@last_description[:params][name.to_sym].merge!(opts) | ||
end | ||
end | ||
end | ||
|
||
end | ||
|
||
end | ||
end | ||
|
||
# load all defined validations | ||
Dir[File.expand_path('../validations/*.rb', __FILE__)].each do |path| | ||
require(path) | ||
end |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
|
||
module Grape | ||
class API | ||
Boolean = Virtus::Attribute::Boolean | ||
end | ||
|
||
module Validations | ||
|
||
class CoerceValidator < SingleOptionValidator | ||
def validate_param!(attr_name, params) | ||
new_value = coerce_value(@option, params[attr_name]) | ||
if valid_type?(new_value) | ||
params[attr_name] = new_value | ||
else | ||
throw :error, :status => 400, :message => "invalid parameter: #{attr_name}" | ||
end | ||
end | ||
|
||
private | ||
def _valid_array_type?(type, values) | ||
values.all? do |val| | ||
_valid_single_type?(type, val) | ||
end | ||
end | ||
|
||
|
||
def _valid_single_type?(klass, val) | ||
if klass == Virtus::Attribute::Boolean | ||
val.is_a?(TrueClass) || val.is_a?(FalseClass) | ||
else | ||
val.is_a?(klass) | ||
end | ||
end | ||
|
||
def valid_type?(val) | ||
if @option.is_a?(Array) | ||
_valid_array_type?(@option[0], val) | ||
else | ||
_valid_single_type?(@option, val) | ||
end | ||
end | ||
|
||
def coerce_value(type, val) | ||
converter = Virtus::Attribute.build(:a, type) | ||
converter.coerce(val) | ||
|
||
# not the prettiest but some invalid coercion can currently trigger | ||
# errors in Virtus (see coerce_spec.rb) | ||
rescue => err | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can do this without a begin? I learned something :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes I was also glad when I found that, nice shortcut. |
||
nil | ||
end | ||
|
||
end | ||
|
||
end | ||
end |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
module Grape | ||
module Validations | ||
|
||
class PresenceValidator < Validator | ||
def validate_param!(attr_name, params) | ||
unless params.has_key?(attr_name) | ||
throw :error, :status => 400, :message => "missing parameter: #{attr_name}" | ||
end | ||
end | ||
|
||
end | ||
|
||
end | ||
end |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
module Grape | ||
module Validations | ||
|
||
class RegexpValidator < SingleOptionValidator | ||
def validate_param!(attr_name, params) | ||
if params[attr_name] && !( params[attr_name].to_s =~ @option ) | ||
throw :error, :status => 400, :message => "invalid parameter: #{attr_name}" | ||
end | ||
end | ||
end | ||
|
||
end | ||
end |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you want to create a
validators
folder and put all these validators into separate files.Update: saw you did this further. I believe the
SingleOptionValidator
should move out too.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I kept SingleOptionValidator there to clearly separate the foundation classes and the real validators but I can move it too if you prefer.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't feel strongly about it. Keep it.