Optional and, or terms #194

ssendev opened this Issue Nov 17, 2012 · 7 comments


None yet

3 participants


if PredicateOperators where changed to return self if other is nil things like

where{(group.eq "group") & (name.eq my{name} if my{name})}

could be written.

I am not sure how to handle it if the first element is optional, the easy way would be to include a NoOp which could be prepended


you can use local variables in squeel dsl blocks, so the following should probably work (assuming &= gets substituted properly)

where{a = (group.eq "group"); a &= name.eq(my{name}) if my{name};a}

nice solution. I came up with

where{[(group.eq "group"), (name.eq my{name} if my{name})].compact.inject(&:&)}

but neither is as readable as the suggested fix


Yeah, but it might be counter-intuitive considering regular & semantics. Consider true & false == false, meaning it should never match anything.


Maybe a little but I think it is fairly easy to grasp that the if discards the complete "& foo" and does not produce "& false". (edit: i screwed up and what was here was invalid)

On the other hand if someone does not intend to use optional conditions and somehow produces & nil it might not be obvious what happened.

I would still include the functionality but that will be decided by somebody else


a hackish solution would be to have where{no_op & foo} and have the no_op trigger the &, | behaviour

ActiveRecord Hackery member

I'd suggest the ifs and such sit outside the Squeel DSL block. Particularly since this example is an AND, I'd say trying to write conditionals that are based on values from outside the block is making the code less readable than simply calling where multiple times with a conditional on some calls.

@ernie ernie closed this Nov 18, 2012

To help the next one having the same problems as I had I have added the examples to the Tips & Tricks Wiki page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment