grape icon indicating copy to clipboard operation
grape copied to clipboard

custom validators won't autoload

Open yanyingwang opened this issue 10 years ago • 6 comments

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.

yanyingwang avatar Aug 12 '15 08:08 yanyingwang

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.

dblock avatar Aug 13 '15 13:08 dblock

'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.

yanyingwang avatar Aug 14 '15 01:08 yanyingwang

As a workaround, I have to call AlphaNumeric before code requires :text, alpha_numeric: true to make sure AlphaNumeric class auto loaded.

yanyingwang avatar Aug 14 '15 01:08 yanyingwang

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).

keenahn avatar Feb 10 '17 10:02 keenahn

No progress AFAIK

dblock avatar Feb 10 '17 15:02 dblock

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.

ngan avatar Sep 02 '21 21:09 ngan