Skip to content

Instantly share code, notes, and snippets.

@plexus
Created October 29, 2014 15:37
Show Gist options
  • Save plexus/60bd6cdf0327a345373f to your computer and use it in GitHub Desktop.
Save plexus/60bd6cdf0327a345373f to your computer and use it in GitHub Desktop.
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