grape
grape copied to clipboard
custom validators won't autoload
Custom Validators
class AlphaNumeric < Grape::Validations::Base
def validate_param!(attr_name, params)
unless params[attr_name] =~ /^[[:alnum:]]+$/
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must consist of alpha-numeric characters"
end
end
end
params do
requires :text, alpha_numeric: true
end
This part of code is from Grape's Readme doc.
The problem is, when requires :text, alpha_numeric: true is call, AlphaNumeric won't be autloaded, because of method 'alpha_numeric' called, not Class 'AlphaNumeric'.
Please let me know if I was wrong.
But if you explicitly require it, it will work right? I think Grape should attempt to auto-load a class if there's no alpha_numeric method already present. Maybe you can try and build a test case for this? I think you can add a path to $LIB or something like that in a test and expect it to try and load the class from there.
'require' works. And also, if code is like this requires :text, AlphaNumeric.validation :true, everything will be OK. I'll post my test case ASAP.
As a workaround, I have to call AlphaNumeric before code requires :text, alpha_numeric: true to make sure AlphaNumeric class auto loaded.
Hi, sorry to bring up a necro thread. Is there any progress on this issue, perhaps in someone else's fork?
It's pretty annoying to just call e.g. AlphaNumeric to force it to autoload. This also violates my linting rules in rubocop (no void context).
No progress AFAIK
I don't think Grape custom validators are reloadable (there's a global registery that never gets reset) so you probably shouldn't put it in app/ since everything in there is expected to be autoloaded and reloadable.
You should put these custom validators in lib/... and require them in an initializer.