Skip to content

Instantly share code, notes, and snippets.

@sinsoku
Last active May 7, 2020 17:31
Show Gist options
  • Save sinsoku/22c299c5f4db450ffc216344d6d7c1ca to your computer and use it in GitHub Desktop.
Save sinsoku/22c299c5f4db450ffc216344d6d7c1ca to your computer and use it in GitHub Desktop.
`map { |x| bar(foo(x)) }` to `map > :foo >> :bar`
require 'binding_of_caller'
module EnumeratorPipeline
class Builder
def initialize(name)
@callbacks = []
@callbacks << binding.of_caller(1).method(name)
end
def >>(name)
@callbacks << binding.of_caller(1).method(name)
self
end
def apply(enumerator)
enumerator.each do |item|
@callbacks.inject(item) { |result, callback| callback.call(result) }
end
end
end
refine Enumerator do
def >(other)
other.is_a?(Builder) ? other.apply(self) : super
end
end
refine Symbol do
def >>(other)
Builder.new(self) >> other
end
end
end
using EnumeratorPipeline
def plus_one(x)
x + 1
end
def double(x)
x * 2
end
pp [1, 2, 3, 4].map > :plus_one >> :double
#=> [4, 6, 8, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment