Params validations for Ruby on Rails.
Add this line to your application's Gemfile:
gem 'validate_params'
And then execute:
$ bundle
In your controller:
class ExamplesController < ApplicationController
include ValidateParams
def create
validate_params! :example
# [...]
end
end
You can rescue from exception like this:
class ApplicationController < ActionController::Base
rescue_from InvalidParamsException do |exception|
respond_to do |format|
format.json { render json: { error: exception.to_s }, status: 400 }
format.html { raise ActionController::RoutingError.new('Not found') }
end
end
end
validate_params! :user
validate_params! :user, :token
validate_params! user: Array
validate_params! user: { type: Array }
validate_params! user: Array, token: String
validate_params! example: { type: Array, size: 2 }
validate_params! number: { range: 0..10 }
validate_params! example: { in: %w(value1 value2) }
validate_params! example: { regex: /myregex/ }
validate_params! example: { custom: Proc.new { |value| value == 'a' } }
validate_params! example: { default: 'abc' }
# :Integer :Float or :Array
validate_params! example: { cast: :Integer }
- Add a
validate_params
method (without!
) that returns false - Config custom exception class
Bug reports and pull requests are welcome on GitHub at https://github.com/rdelandesen/validate_params.
The gem is available as open source under the terms of the MIT License.