-
-
Save sshkarupa/4ef91e0871828c292fbe2b692dc314c5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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 [email protected]? | |
| @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