I'm trying to define a DSL where rules (for the sake of this example, the rules define whether something is "good" or "bad") are specified in a block in Ruby. The following is a (grossly simplified) version of what I want to do:
def test_block
# Lots of other code
is_good = yield # ... should give me true or false
# Lots of other code
end
test_block do
good if some_condition
good if some_other_condition
bad
end
Is there any way I can define methods good and bad that make the block break? In the above example, I want to:
- check if some_condition is true, and if it is, break out of the block and have it return true
- check if some_other_condition is true, and if it is, break out of the block and have it return true
- return false from the block unconditionally if we're still in it
i.e. I want to make the above code behave as if I had written the block like so:
result = test_block do
break true if some_condition
break true if some_other_condition
break false
end
Putting break in the definition of the good/bad method obviously doesn't work. Is there some other way of achieving my desired result or should I think about some entirely different way of going about this?