ControllerValidator
Simple Validations in the Controller!
(Re)Use the familiar ActiveModel::Errors pattern for controller validations, so you already know how this works.
Installation
Add this line to your application's Gemfile:
gem 'controller_validator'
And then execute:
$ bundle
Or install it yourself as:
$ gem install controller_validator
Usage
See the integration specs!
class ThingController < ApplicationController
def create
@thing = Thing.new
validator = ValidateThingOnCreate.new()
validator.validate_and_push_errors_to(instance: @thing)
if @thing.errors.any?
render :new
else
if @thing.save
redirect_to @thing_path(id: @thing.id)
else
render :new
end
end
end
end
class ValidateThingOnCreate < ControllerValidator::Validator
attr_accessor :too_many, :no_bobs
def initialize()
@too_many = Thing.count > 100
@no_bobs = Bob.count == 0
end
def validate!
errors.add(:too_many, "must not be true") if !self.too_many
errors.add(:no_bobs, "must be true") if !self.no_bobs
errors.blank?
end
end
Contributing
- Fork it ( https://github.com/[my-github-username]/controller_validator/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request