Skip to content

Instantly share code, notes, and snippets.

@akitaonrails
Last active February 18, 2016 16:40
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 akitaonrails/812e8380560538b2ec12 to your computer and use it in GitHub Desktop.
Save akitaonrails/812e8380560538b2ec12 to your computer and use it in GitHub Desktop.
Simple Pipe like Operations in Ruby
module Pipe
def pipe(initial_state)
Pipe::PipeChain.new(initial_state, self)
end
class PipeChain
attr_reader :state, :context
def initialize(object, context)
@state = object
@context = context
end
def method_missing(name, *args, &block)
if state.respond_to?(name)
Pipe::PipeChain.new( state.send(name, *args, &block), context)
else
Pipe::PipeChain.new( context.send(name, *([state] + args), &block), context )
end
end
def result
@state
end
end
end
module Hello
extend Pipe
def self.modify_1(a)
a + " called from 1 "
end
def self.modify_2(b, message)
b + " called from 2 with #{message}"
end
def self.modify_3(c)
c + " called from 3 with #{yield(c)}"
end
end
Hello.pipe("foo").
modify_1.
modify_2("custom message").
upcase.
modify_3 { |state| "#{state} called from block" }.
split(" ").
join(" - ").
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment