Created
January 12, 2019 16:00
-
-
Save jeremywrowe/2c069ed8ae6d10024f2fd151538edee6 to your computer and use it in GitHub Desktop.
A light weight pipe implementation 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
#!/usr/bin/env ruby | |
class PipeNode | |
attr_writer :result | |
def initialize(value, chain) | |
@value = value | |
@chain = chain | |
@result = :unknown | |
end | |
def to_s | |
"#{@value}.(#{@chain}) = #{@result}" | |
end | |
end | |
class Pipe | |
def self.>(value:, chain:) | |
new.>(value: value, chain: chain) | |
end | |
def initialize | |
@tree = [] | |
end | |
def >(value: @value, chain:) | |
pipe_node = PipeNode.new(value, chain) | |
@tree << pipe_node | |
begin | |
@value = chain.class == Proc ? chain.call(value) : value.public_send(chain) | |
rescue StandardError => error | |
pipe_node.result = "Error: #{error.message}" | |
print_tree | |
raise | |
end | |
self | |
end | |
def resolve | |
@value | |
end | |
def print_tree | |
puts @tree.map(&:to_s).join(' > ') | |
self | |
end | |
end | |
result = Pipe | |
.>(value: '10', chain: :to_i) | |
.>(chain: :positive?) | |
.>(chain: ->(value) { !value }) | |
.print_tree | |
.resolve | |
puts | |
puts result.inspect | |
puts | |
result_with_error = Pipe | |
.>(value: '10', chain: :to_i) | |
.>(chain: :positive?) | |
.>(chain: ->(value) { raise "boom" }) | |
.resolve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment