Last active
October 20, 2022 15:28
-
-
Save joeldrapper/e2f1eb8fab8f28caf4460b576e0fb41e to your computer and use it in GitHub Desktop.
Object yielders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Object | |
| def then_maybe | |
| yield(self) || self | |
| end | |
| def then_if(condition) | |
| condition ? yield(self) : self | |
| end | |
| def then_unless(condition) | |
| !condition ? yield(self) : self | |
| end | |
| end |
Author
🤔 The only thing is when might sound like we’re doing an equality comparison against self, e.g.
def when(comparator)
if ==(comparator) || is_a?(comparator)
yield(self)
else
self
end
endThis would make sense if we don’t know in advance what we’re calling when on but we want to yield the block if it matches a condition.
I was thinking of it as a blank case statement like:
case
when condition then yield(self)
endBut true, it can be confusing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just realized
then_ifcould potentially also bewhen, e.g.Record.all.when(bar) { _1.where(foo: bar) }, unless it's a keyword.