Last active
February 18, 2016 16:40
-
-
Save akitaonrails/812e8380560538b2ec12 to your computer and use it in GitHub Desktop.
Simple Pipe like Operations in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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