Objecheck
Objecheck provides a simple and extensible object validator
Installation
Add this line to your application's Gemfile:
gem 'objecheck'And then execute:
$ bundle
Or install it yourself as:
$ gem install objecheck
Usage
require 'objecheck'
# Create a validator with rules
validator = Objecheck::Validator.new({
type: Hash
})
# Validator#validate checks the given object and returns error messages as a array
p validator.validate({ a: 1, b: 2 }) # => []
p validator.validate([1, 2]) # => ["root: the type should be a Hash (got Array)"]
# Validate type of keys and values
validator = Objecheck::Validator.new({
each_key: { type: Symbol }
each_value: { type: Integer }
})
p validator.validate({ a: 1, b: 2 }) # => []
# Validate array that contains specific key/value
validator = Objecheck::Validator.new({
type: Array,
each: {
key_value: {
name: {
value: { type: String }
},
age: {
required: false,
value: { type: Integer }
}
}
}
})
p validator.validate([{ name: 'Jhon', age: 20 }, { name: 'Tom' }]) # => []Builtin rules
type
type checks that the object is a given class (by is_a?).
Example schema:
{
type: Hash
}When you want to check that value is a boolean (true or false), use :bool.
{
type: :bool
}each
each checks elements of the object by using each.
Example schema:
{
each: {
type: Integer
}
}each_key
each_key checks keys of the object by using each_key.
Example schema:
{
each_key: {
type: Symbol
}
}each_value
each_value checks values of the object by using each_pair.
Example schema:
{
each_value: {
type: Integer
}
}key_value
key_value checks key/values of the object by using each_pair.
Example schema:
{
key_value: {
name: {
value: { type: String }
},
age: {
required: false # Default is true
value: { type: Integer }
}
}
}eq
eq checks equality of values.
Example schema:
{
eq: 'foo'
}any
any makes disjunction of rules.
Example schema:
{
any: [
{ type: Integer },
{ type: String }
]
}satisfy
satisfy checks by Proc
Example schema:
{
satisfy: ->(x) { x.even? }
}respond_to
respond_to checks defined methods
Example schema:
{
respond_to: [:configure :run]
}regexp
regexp checks pattern by regular expression.
Example schema:
{
regexp: /\A[a-zA-Z_]\w*\z/
}Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/autopp/objecheck.