Skip to content

Instantly share code, notes, and snippets.

@lloydmeta
Created December 24, 2013 02:11
Show Gist options
  • Save lloydmeta/8107876 to your computer and use it in GitHub Desktop.
Save lloydmeta/8107876 to your computer and use it in GitHub Desktop.
Range validator for Grape.
class RangeValidator < Grape::Validations::Validator
def initialize(attrs, options, required, scope)
@range = options
@required = required
raise ArgumentError, "Range provided (#{@range.inspect}) does not implement #cover?" unless @range.respond_to? :cover?
super
end
def validate_param!(attr_name, params)
if (params[attr_name] || @required) && !@range.cover?(params[attr_name])
raise Grape::Exceptions::Validation,
:param => attr_name.to_s,
:message => "#{attr_name} should be within #{@range}"
end
end
end
@lloydmeta
Copy link
Author

Example

# code
params do
  optional :limit, :type => Integer, :default => 10, :range => 1 .. 100, :desc => "retrieve at most +limit+ machines. Defaults to 10, max of 100"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment