resetability
resetability

Reputation: 13

Validate hash keys/values

I am trying to validate the values of certain keys in a hash:

response[:payment_status] == 'Completed' && response[:receiver_email] == '[email protected]' && response[:foo] == 'Bar'

While the above approach works I am quite sure there is a more elegant solution. I would hate to have a really long line if I add extra keys/values I want to validate.

P.S: I should mention I want a simple true/false returned.

Upvotes: 1

Views: 4763

Answers (3)

Augustin Riedinger
Augustin Riedinger

Reputation: 22188

If you want to test equality on each element, there is an elegant solution:

response.slice(:payment_status, :receiver_email, :foo) == { :payment_status => 'Completed', :receiver_email => '[email protected]', :foo => 'Bar'}

In my case, I need to compare inequality too. It can be done by calling BasicObject#instance_eval.

Then it writes:

response.instance_eval{ |hash| hash[:payment_status] != 'Pending' && hash[:receiver_email] == '[email protected]' && hash[:boolean_result] }

Upvotes: 0

James Brooks
James Brooks

Reputation: 658

This might help you out with validating hashes using another hash to define the structure/types that you expect (also works with nested hashes):

https://github.com/JamesBrooks/hash_validator

Upvotes: 1

Lee
Lee

Reputation: 144136

You could create a hash of the expect key/values and then map the input hash values:

expected = {'payment_status' => 'Completed', 'receiver_email' => '[email protected]' ... }
valid = expected.keys.all? {|key| response[key] == expected[key]}

Upvotes: 1

Related Questions