deseretbook / classy_hash Goto Github PK
View Code? Open in Web Editor NEWKeep Your Hashes Classy (a lightweight Hash validation gem)
License: MIT License
Keep Your Hashes Classy (a lightweight Hash validation gem)
License: MIT License
Consider:
schema = {
key1: ClassyHash::G.composite(
String,
ClassyHash::G.length(4..20),
},
}
This would allow simple constraints to be combined in powerful ways.
Just a feature suggestion; I'm happy to code it up as a PR, but, like the other one, wanted to see if this is in line with your vision for your gem.
(BTW, this gem seems really cool. I've been looking for lightweight schema validation for a while, in order to efficiently sanitize API inputs)
Hi, looks like a really nice lib.
Is there a way of checking for a key to be absent?
I have a very simple schema that follows this basic pattern:
SCHEMA = {
collection: [[ { id: Integer } ]]
}.freeze
and I notice that even when validating strictly, no errors are raised for objects such as:
invalid = { collection: [{ id: 1, wutang: true }] }
ClassyHash.validate_strict(invalid, SCHEMA)
# => nil
Peeking into the source, I noticed this, and was wondering if you would consider supporting a deep version of validate_strict
?
Hi โ thanks for this succinct, performant and very useful library ๐
Is it possible to check for the presence of a field conditionally? A concrete example below:
schema = {
name: String,
field_type: Set.new(['text', 'select']),
options: <should only be present if field_type == 'select'>,
multiple: <should only be present if field_type == 'select'>
}
I know you can use a Proc
/lambda
, but it doesn't look like you can access the hash being validated (or ideally, the current hash the field is in, so you can check siblings)? Not sure yet what an elegant solution might be for this particular problem.
Would appreciate your thoughts on how to solve this.
It would be awesome if, when validation fails, the exception raised contained a reference to all the keys whose value failed to validate. Example:
schema = {
key1: String,
key2: Integer,
key3: TrueClass
}
bad_data = {
key3: true
}
begin
ClassyHash.validate(bad_data, schema)
# Consuming code could rescue a ClassyHash specific error
rescue ClassyHash::ValidationError => error
# error.message is ":key1 is not a String, :key2 is not an Integer"
# error[:key1] is ["is not a String"], error[:key2] is "is not an Integer"
end
The primary value would be that if the hash fails validation, the programmer can look at all the errors at once, rather than correcting them one at a time. The secondary benefit would be that, for example, API clients and web forms can display all the errors to the end user.
If were to code up a pull request for this, would you consider the functionality? I want to make sure this is in line with your vision for the gem. In README.md
:
Validation proceeds until the first invalid value is found, then an error is thrown for that value. Later values are not checked.
So I'm not sure you would actually want this functionality.
Thanks for the gem!
Hi, I am trying to validate some Hashes, which are used to initialize objects. I would like to return a useful error message to the User like "each container resource needs a distinct name" or sth. Is there any possibility, to achieve that with classy_hash or do you have a hint where to implement that Feature?
Regards, Marco
Is there a way of declaring that there could be any key that is a number but the value has to be validated by a schema?
I want to validate data that come from a website I'm scraping, and it has a field that maps certain ids to values.
Example:
schema = {
[Integer]: { id: Integer }
}
# valid hash
{
43214321: { id: 1234}
}
#invalid hash
{
'test': { id: 1234}
}
#invalid hash
{
43214321: { id: 'test'}
}
While working with ClassyHash on a project, I encountered a need for something a bit more straightforward for handling a key with a set of allowed options in the form of Symbols. I wanted to be able to write something like:
schema = {
test: Set.new([:hello, :world])
}
source = {
test: :hello
}
After a little research, I figured out that injecting the following into classy_hash.rb solves the problem very easily:
def self.check_one(key, value, constraint, parent_path=nil)
case constraint
...
when Set
self.raise_error(parent_path, key, "is not valid. The value #{value} is not a member of #{constraint.inspect}") unless constraint.include?(value)
Example error:
/home/john/.rvm/gems/ruby-2.1.5/gems/classy_hash-0.1.5/lib/classy_hash.rb:178:in `raise_error': :hello is not valid. The value 1 is not a member of #<Set: {:one, :two}> (RuntimeError)
I'll be using this as a patched version of ClassyHash and wanted to offer it to you as a possible addition.
Best,
John Elrick
Perhaps this is implementation error, but I have a situation similar to this:
> child_schema_one = { type: CH::G.enum('one') }
> child_schema_two = { type: CH::G.enum('two') }
> parent_schema = { children: [[child_schema_one, child_schema_two]] }
> hash = { children: [{ type: 'two'}] }
>
> ClassyHash.validate_strict(hash, parent_schema)
RuntimeError: :children[0][:type] is not an element of ["one"]
I had expected each schema to be checked before raising. Is there a way to achieve this?
WARNING: Using the raise_error
matcher without providing a specific error or message risks false positives, since raise_error
will match when Ruby raises a NoMethodError
, NameError
or ArgumentError
, potentially allowing the expectation to pass without even executing the method you are intending to call. Instead consider providing a specific error class or message. This message can be supressed by setting: RSpec::Expectations.configuration.warn_about_potential_false_positives = false
.
Called from /home/travis/build/deseretbook/classy_hash/spec/lib/classy_hash_spec.rb:522:in `block (3 levels) in <top (required)>'.
Ruby 2.4 merges Fixnum
and Bignum
into Integer
. This breaks the msgpack gem, and will affect some of the logic of the RSpec tests.
Fixnum
and Bignum
, or limit them to older Ruby versions.Hello,
I have a requirement wherein different users in my application would like to configure their own validation requirements in my app. Would this gem be suitable for storing such configuration managed from a UI? I would then be applying the validation checking against already created model objects.
Thanks
It looks like ClassyHash is still building on travis-ci.org. They are migrating everyone to travis-ci.com, and removing free open source builds.
I'm opening this issue as a note for future development and for testing on new Ruby versions that it will be necessary to move CI to another platform, e.g. GitHub Actions or CircleCI.
Hi! I have a case where the schema of one key depends on the value of another key. Is it possible to do so?
Example:
SCHEMA
{
type: String,
additionalOptions: lambda do |hash|
if hash[:type] == 'car'
{ numberOfWindows: Integer }
elsif hash[:type] == 'motorcycle'
{}
end
end
}
VALID
{
type: 'car',
additionalOptions: {
numberOfWindows: 4
}
{
type: 'motorcycle',
additionalOptions: {}
}
INVALID
{
type: 'car',
additionalOptions: {}
}
{
type: 'motorcycle',
additionalOptions: {
numberOfWindows: 0
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.