Skip to content

Instantly share code, notes, and snippets.

@EdwardDiehl
Forked from sclinede/simple_railway.rb
Created January 5, 2019 08:56
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 EdwardDiehl/0611877b50c9da937a4854638eb6cd29 to your computer and use it in GitHub Desktop.
Save EdwardDiehl/0611877b50c9da937a4854638eb6cd29 to your computer and use it in GitHub Desktop.
module SimpleRailway
class Result
attr_accessor :success, :data
def initialize(success, data)
@success = success
@data = data
end
def success?; !!success; end
def failure?; !success?; end
def self.success(data = nil)
new(true, data)
end
def self.failure(data = nil)
new(false, data)
end
end
class Chain
def initialize
@result = Result.success
@store = []
end
def call
while !@store.empty?
@store.shift.tap do |action|
@result = action.call unless @result.failure?
end
end
@result
end
def push(&block)
@store << block
end
end
def initialize(*)
reset_chain!
super
end
def reset_chain!
@chain = Chain.new
end
def run
@chain.call
end
def chain
@chain.push { yield(self) } if block_given?; self
end
def when_success
yield(run.data) if run.success?; self
end
def when_failure
yield(run.data) if run.failure?; self
end
protected
def Success(data)
Result.success(data)
end
def Failure(data)
Result.failure(data)
end
end
class Counter
prepend SimpleRailway
attr_reader :count
def initialize
reset!
end
def reset!
@count = 0
end
def increment
return Failure("Overflow !@$^&") if @count >= 3
puts "+1"
Success(@count += 1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment