Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/e77f80e4a84925ff0044 to your computer and use it in GitHub Desktop.
Save baweaver/e77f80e4a84925ff0044 to your computer and use it in GitHub Desktop.
Pipe an object through a block only if condition is true. Like the pipe which simply yields self.
class Object
def conditional_pipe(condition, &block)
condition ? yield(self) : self
end
def true_tap(&block)
self && yield(self)
self
end
def false_tap(&block)
self || yield(self)
self
end
end
"foobar".conditional_pipe(true) { |s| s.sub(/foo/, 'baz') }
#=> "bazbar"
"foobar".conditional_pipe(false) { |s| s.sub(/foo/, 'baz') }
#=> "foobar"
true.false_tap { |v| puts v }
#=> true
true.true_tap { |v| puts v }
# true
#=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment