Skip to content

Instantly share code, notes, and snippets.

@duckinator

duckinator/x.rb Secret

Created November 4, 2013 20:06
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 duckinator/d08df4d312139a447738 to your computer and use it in GitHub Desktop.
Save duckinator/d08df4d312139a447738 to your computer and use it in GitHub Desktop.
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