How to avoid short-circuit evaluation on

Flackou picture Flackou · Jan 28, 2009 · Viewed 7.8k times · Source

I'm working with Ruby on Rails and would like to validate two different models :

if (model1.valid? && model2.valid?)
...
end

However, "&&" operator uses short-circuit evaluation (i.e. it evaluates "model2.valid?" only if "model1.valid?" is true), which prevents model2.valids to be executed if model1 is not valid.

Is there an equivalent of "&&" which would not use short-circuit evaluation? I need the two expressions to be evaluated.

Answer

Codebeef picture Codebeef · Jan 28, 2009

Try this:

([model1, model2].map(&:valid?)).all?

It'll return true if both are valid, and create the errors on both instances.