From e20326d5778a3a21c6a44e7e2867247244543c54 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 27 Jul 2012 19:16:44 -0700 Subject: [PATCH] Added the Confirm built-in middleware This middleware asks the user a question and expects a Y/N answer. This middleware can be used with the Call middleware. --- lib/vagrant/action.rb | 1 + lib/vagrant/action/builtin/confirm.rb | 28 +++++++++++++++++++ .../vagrant/action/builtin/confirm_test.rb | 21 ++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 lib/vagrant/action/builtin/confirm.rb create mode 100644 test/unit/vagrant/action/builtin/confirm_test.rb diff --git a/lib/vagrant/action.rb b/lib/vagrant/action.rb index aeb44ce29..9cc2641c4 100644 --- a/lib/vagrant/action.rb +++ b/lib/vagrant/action.rb @@ -16,6 +16,7 @@ module Vagrant # and are thus available to all plugins as a "standard library" of sorts. module Builtin autoload :Call, "vagrant/action/builtin/call" + autoload :Confirm, "vagrant/action/builtin/confirm" end module Env diff --git a/lib/vagrant/action/builtin/confirm.rb b/lib/vagrant/action/builtin/confirm.rb new file mode 100644 index 000000000..d877f9dea --- /dev/null +++ b/lib/vagrant/action/builtin/confirm.rb @@ -0,0 +1,28 @@ +module Vagrant + module Action + module Builtin + # This class asks the user to confirm some sort of question with + # a "Y/N" question. The only parameter is the text to ask the user. + # The result is placed in `env[:result]` so that it can be used + # with the {Call} class. + class Confirm + # For documentation, read the description of the {Confirm} class. + # + # @param [String] message The message to ask the user. + def initialize(app, env, message) + @app = app + @message = message + end + + def call(env) + # Ask the user the message and store the result + choice = nil + choice = env[:ui].ask(@message) + env[:result] = choice && choice.upcase == "Y" + + @app.call(env) + end + end + end + end +end diff --git a/test/unit/vagrant/action/builtin/confirm_test.rb b/test/unit/vagrant/action/builtin/confirm_test.rb new file mode 100644 index 000000000..7c290e172 --- /dev/null +++ b/test/unit/vagrant/action/builtin/confirm_test.rb @@ -0,0 +1,21 @@ +require File.expand_path("../../../../base", __FILE__) + +describe Vagrant::Action::Builtin::Confirm do + let(:app) { lambda { |env| } } + let(:env) { { :ui => double("ui") } } + let(:message) { "foo" } + + ["y", "Y"].each do |valid| + it "should set the result to true if '#{valid}' is given" do + env[:ui].should_receive(:ask).with(message).and_return(valid) + described_class.new(app, env, message).call(env) + env[:result].should be + end + end + + it "should set result to false if anything else is given" do + env[:ui].should_receive(:ask).with(message).and_return("nope") + described_class.new(app, env, message).call(env) + env[:result].should_not be + end +end