Skip to content

Instantly share code, notes, and snippets.

@duckinator duckinator/x.rb Secret
Created Nov 4, 2013

Embed
What would you like to do?
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
You can’t perform that action at this time.