You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I usually define a method with all the logic to custom validate the keys in this case. Then I use a lambda to call that method and validate the key. Something like:
require'hash_validator'# the data you providedVALID_FOO=[1,2]VALID_BAR=[3,4]valid_a={foo: [1,2],bar: [3,4]}valid_b={}valid_c={foo: [1]}valid_d={bar: [3]}invalid_a={foo: 1}invalid_b={bar: 1}invalid_c={bar: [1]}# assembling an array with your samplessamples=[valid_a,valid_b,valid_c,valid_d,invalid_a,invalid_b,invalid_c]# the expected hash with lambdasexpected={foo: ->(value){foo_validationvalue},bar: ->(value){bar_validationvalue}}# methods with the logic of the validationdeffoo_validation(value)returntrueunlessvaluevalue.each{ |v| returnfalseunlessVALID_FOO.include?v}ifvalue.is_a?Arrayenddefbar_validation(value)returntrueunlessvaluevalue.each{ |v| returnfalseunlessVALID_BAR.include?v}ifvalue.is_a?Arrayend# validating each of the samples you providedsamples.eachdo |sample|
val=HashValidator.validate(sample,expected)putsval.valid?putsval.errorsend
If you run this code, you'll see that the first four hashes are OK, and the other three are invalid, just like you want.
Also, you can write a custom validator and use it just like the others.
Suppose I have a hash that has optional keys, but the keys that are provided must be in a list if they are provided.
VALID_FOO = [ONE,TWO]
VALID_BAR = [THREE,FOUR]
valid_hash = { foo: [ONE,TWO], bar: [THREE,FOUR]}
also_valid = {}
also_valid = {foo: [ONE]}
also_valid = {bar: [THREE]}
invalid = {foo: ONE}
invalid_also = {bar: ONE}
invalid_also = {bar: [ONE]}
Thus, bar and foo keys are optional. However, if they exist, they must be an array, whose values are in VALID_FOO or VALID_BAR as appropriate.
How would we specify that validation?
The text was updated successfully, but these errors were encountered: