Thrift::Validator
Recursive thrift struct validator. The thrift library out of the box does not validated nested structs, this library fixes that problem. It does not monkey-patch the Thrift code. Instead this library includes a class to recursively validate objects.
Here's an example from this libraries test. Take a look at this protocol:
struct SimpleStruct {
1: required string required_string
2: optional string optional_string
}
struct NestedExample {
1: required SimpleStruct required_struct
2: optional SimpleStruct optional_struct
}
Then ran some ruby:
struct = SimpleStruct.new
nested = NestedStruct.new required_struct: struct
# Method defined by the thrift library
struct.validate # => Thrift::ProtocolException
# Thrift only validate fields set as required on this instance.
# so since required_struct is non-nil validation succeeds.
# Also note that thrift does not validate the semantics of
# the assigned objects, so also assigning and invalid struct will
# pass its validation method.
nested.validate # => true
# With the validator
validator = Thrift::Validator.new
validator.validate nested # => Thrift::ProtocolException
Semantics
- Original thrift validation smenatics enforces
-
optional
orrequired
struct
types pass validation -
optional
orrequired
list<struct>
items pass validation -
optional
orrequired
set<struct>
items pass validation -
optional
orrequired
map
type using astruct
for key or value pass validation
Exception handling
Due to the recursive nature of thrift-validator
, the validation
errors raised by Thrift have become less than helpful. In order
to provide more information, the Thrift::ProtocolException
's
message is prefixed with the type where the error occurred. For
example:
# Without thrift-validator
> struct.validate
Thrift::ProtocolException: Required field required_string is unset!
# With thrift-validator
> Thrift::Validator.new.validate(struct)
Thrift::ProtocolException: SimpleStruct: Required field required_string is unset!
This feature becomes especially useful with nested structures, where the validation may fail at any given depth.
Installation
Add this line to your application's Gemfile:
gem 'thrift-validator'
And then execute:
$ bundle
Or install it yourself as:
$ gem install thrift-validator
Testing
First install thrift
compilier on your platform.
$ make test
Contributing
- Fork it ( https://github.com/saltside/thrift-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