Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Needs more examples beyond simple #5

Closed
nielsm opened this issue Feb 5, 2015 · 1 comment
Closed

Needs more examples beyond simple #5

nielsm opened this issue Feb 5, 2015 · 1 comment

Comments

@nielsm
Copy link

nielsm commented Feb 5, 2015

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?

@samuel-hcl
Copy link
Contributor

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 provided
VALID_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 samples
samples = [valid_a, valid_b, valid_c, valid_d, invalid_a, invalid_b, invalid_c]

# the expected hash with lambdas
expected = {
  foo: ->(value) { foo_validation value },
  bar: ->(value) { bar_validation value }
}

# methods with the logic of the validation
def foo_validation(value)
  return true unless value
  value.each { |v| return false unless VALID_FOO.include? v } if value.is_a? Array
end

def bar_validation(value)
  return true unless value
  value.each { |v| return false unless VALID_BAR.include? v } if value.is_a? Array
end

# validating each of the samples you provided
samples.each do |sample|
  val = HashValidator.validate(sample, expected)
  puts val.valid?
  puts val.errors
end

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants