From efc1bf50dd9a8439f9dafae43ee340891c131792 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sat, 8 Feb 2014 14:03:31 -0800 Subject: [PATCH] core: Machine#with_ui --- lib/vagrant/machine.rb | 17 +++++++++++++++++ test/unit/vagrant/machine_test.rb | 14 ++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/vagrant/machine.rb b/lib/vagrant/machine.rb index e0728aafb..3f084caba 100644 --- a/lib/vagrant/machine.rb +++ b/lib/vagrant/machine.rb @@ -1,3 +1,5 @@ +require "thread" + require "log4r" module Vagrant @@ -103,6 +105,7 @@ module Vagrant @provider_name = provider_name @provider_options = provider_options @ui = Vagrant::UI::Prefixed.new(@env.ui, @name) + @ui_mutex = Mutex.new # Read the ID, which is usually in local storage @id = nil @@ -337,5 +340,19 @@ module Vagrant raise Errors::MachineStateInvalid if !result.is_a?(MachineState) result end + + # Temporarily changes the machine UI. This is useful if you want + # to execute an {#action} with a different UI. + def with_ui(ui) + @ui_mutex.synchronize do + begin + old_ui = @ui + @ui = ui + yield + ensure + @ui = old_ui + end + end + end end end diff --git a/test/unit/vagrant/machine_test.rb b/test/unit/vagrant/machine_test.rb index 8e48dd511..1c723166f 100644 --- a/test/unit/vagrant/machine_test.rb +++ b/test/unit/vagrant/machine_test.rb @@ -445,4 +445,18 @@ describe Vagrant::Machine do to raise_error(Vagrant::Errors::MachineStateInvalid) end end + + describe "#with_ui" do + it "temporarily changes the UI" do + ui = Object.new + changed_ui = nil + + subject.with_ui(ui) do + changed_ui = subject.ui + end + + expect(changed_ui).to equal(ui) + expect(subject.ui).to_not equal(ui) + end + end end