Project

objecheck

0.0
No commit activity in last 3 years
No release in over 3 years
schema and validator for a Ruby object
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

~> 1.16
~> 10.0
~> 3.0
 Project Readme

Objecheck

Gem Version CircleCI

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.

License

Apache License 2.0