Violated
Violated is a simple gem to do validation of any object.
Installation
Add this line to your application's Gemfile:
gem 'violated'
And then execute:
$ bundle
Or install it yourself as:
$ gem install violated
Usage
Quick start
Add validation to any object by including Violated.new
:
class Person
include Violated.new
end
Then you can define the violations like this:
class Person
attr_reader :name
include Violated.new
violate(:name).when_not :present
end
Or multiple per field:
class Person
attr_reader :name
include Violated.new
violate(:name).when_not :present, [:unique, ->(attr) { uniqueness_check_for_your_application }]
end
You can see if the object is valid:
person.valid?
and lookup the violations if not:
person.violations
Built-in validators
:present
violate(:attr).when_not :present
This fails with a required reason, when the attribute is not present.
:unique
violate(:attr).when_not [:unique, ->(attr) { uniqueness_check_for_your_application }]
This fails with a duplicate reason, when the lambda given returns true.
Creating your own validators
First create the validator, a validator must be at least initialized with a field and it must respond to validate with an object:
class CustomValidator
def initialize(field)
@field = field
end
def validate(object)
object.violations << Violated::Violation.new(@field, :custom) if object.violates?(@field)
end
end
Register it with the Registry
:
Violated::Registry.register :custom, CustomValidator
Use it in your class:
class Person
attr_reader :name
include Violated.new
violate(:name).when_not :custom
end
Contributing
- Fork it ( https://github.com/ThijsWouters/violated/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