Skip to content

Instantly share code, notes, and snippets.

@cesarfigueroa
Last active December 14, 2015 23:39
Show Gist options
  • Save cesarfigueroa/5167627 to your computer and use it in GitHub Desktop.
Save cesarfigueroa/5167627 to your computer and use it in GitHub Desktop.
Grape length validator
class Length < Grape::Validations::SingleOptionValidator
def validate_param!(attr_name, params)
case @option
when Integer
unless params[attr_name].to_s.length == @option
throw :error, :status => 400,
:message => "#{attr_name} must be #{@option} characters long"
end
when Range
unless @option.include?(params[attr_name].to_s.length)
throw :error, :status => 400,
:message => "#{attr_name} must be between #{@option.begin} and #{@option.end} characters long"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment