Created
October 29, 2014 15:37
-
-
Save plexus/60bd6cdf0327a345373f 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
module Yaks | |
# State monad-ish thing. | |
class StatefulBuilder < BasicObject | |
def create(*args, &block) | |
@state = @klass.create(*args) | |
instance_eval(&block) | |
@state | |
end | |
def initialize(klass, methods) | |
@klass = klass | |
mod = ::Module.new | |
mod.__send__(:extend_object, self) | |
mod.module_exec(klass, methods) { |klass, methods| | |
methods.each do |method_name| | |
define_method method_name do |*args, &block| | |
@state = @state.public_send(method_name, *args, &block) | |
unless @state.is_a?(@klass) | |
::Kernel.raise ::Yaks::IllegalState, "#{@klass}##{method_name}(#{args.map(&:inspect).join(', ')}) returned #{@state.inspect}. Expected instance of #{@klass}" | |
end | |
end | |
end | |
} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment