开发者

Validate hash keys/values

I am trying to validate the values of certain keys in a h开发者_如何学JAVAash:

response[:payment_status] == 'Completed' && response[:receiver_email] == 'test@example.com' && 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.


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

expected = {'payment_status' => 'Completed', 'receiver_email' => 'test@example.com' ... }
valid = expected.keys.all? {|key| response[key] == expected[key]}


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


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 => 'test@example.com', :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] == 'test@example.com' && hash[:boolean_result] }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜