Skip to content

Instantly share code, notes, and snippets.

@joeldrapper
Last active October 20, 2022 15:28
Show Gist options
  • Save joeldrapper/e2f1eb8fab8f28caf4460b576e0fb41e to your computer and use it in GitHub Desktop.
Save joeldrapper/e2f1eb8fab8f28caf4460b576e0fb41e to your computer and use it in GitHub Desktop.
Object yielders
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
@joeldrapper
Copy link
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
end

This 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.

@kaspth
Copy link

kaspth commented May 6, 2022

I was thinking of it as a blank case statement like:

case
when condition then yield(self)
end

But true, it can be confusing.

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