Skip to content

Instantly share code, notes, and snippets.

@melborne
Last active August 29, 2015 13:57
Show Gist options
  • Save melborne/9363948 to your computer and use it in GitHub Desktop.
Save melborne/9363948 to your computer and use it in GitHub Desktop.
Pipeline in Ruby
class Filter
class << self
def filters
@filters ||= {}
end
def add(name, &code)
filters[name] = code
end
end
def initialize(obj)
@methods = []
@obj = obj
end
def |(method)
@methods << method
self
end
def run
@methods.inject(@obj) do |mem, method|
if custom = Filter.filters[method]
custom.call(mem)
else
mem.send method
end
end
end
def to_s
run.to_s
end
end
module CoreExt
[Fixnum, Float, String].each do |klass|
refine klass do
def |(other)
return super unless other.is_a?(Symbol)
Filter.new(self) | other
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment