I have a Rails 4 project which uses Grape for API stuff, I want to do some custom validations as described in the grape documentation. I want to know where should I place my custom validations code (like in lib file) and will I need to include or require something to use it inside my API file?
The documentation tells you to make a class but I am confused about the file structure if I have to write many custom validations.
The last time I used Grape I added custom validations to lib, I then required them into any API classes that used them. Eg:
lib/api/validations/minimum_value.rb
class AlphaNumeric < Grape::Validations::Validator
def validate_param!(attr_name, params)
unless params[attr_name] =~ /^[[:alnum:]]+$/
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must consist of alpha-numeric characters"
end
end
end
app/api/twitter.rb
class Twitter::API < Grape::API
require_relative '../../lib/api/validations/minimum_value'
Of course you may want to add lib/api/validations
to the auto-loader to prevent having to manually require.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments