-
-
Save duckinator/d08df4d312139a447738 to your computer and use it in GitHub Desktop.
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
class Chain | |
class InvalidChain < Exception; end | |
CHAINS = [ | |
"as_long_as", | |
] | |
def initialize(*args, &block) | |
@args = args | |
@block = block | |
@chain = [] | |
end | |
def previous(previous) | |
@chain = [previous, *@chain] | |
end | |
def try_chain | |
chain_name = @chain.map(&:to_s).join('_') | |
if CHAINS.include?(chain_name) | |
send(chain_name, *@args, &@block) | |
else | |
raise InvalidChain | |
end | |
end | |
def as_long_as(condition, action) | |
action.call while condition.call | |
end | |
end | |
def chain(method, *args, &block) | |
x = args[0] | |
unless x.is_a?(Chain) | |
x = Chain.new(*args, &block) | |
end | |
x.previous(method) | |
begin | |
x.try_chain | |
rescue Chain::InvalidChain | |
x | |
end | |
end | |
def as(*args, &block) | |
chain(:as, *args, &block) | |
end | |
def long(*args, &block) | |
chain(:long, *args, &block) | |
end | |
i = 0 | |
as long as -> { i < 10 }, -> { puts i+=1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment