diff --git a/lib/vagrant/machine_index.rb b/lib/vagrant/machine_index.rb index 9be88dbb5..c7ad6f31a 100644 --- a/lib/vagrant/machine_index.rb +++ b/lib/vagrant/machine_index.rb @@ -34,6 +34,8 @@ module Vagrant # } # class MachineIndex + include Enumerable + # Initializes a MachineIndex at the given file location. # # @param [Pathname] data_dir Path to the directory where data for the @@ -82,6 +84,15 @@ module Vagrant true end + # Iterate over every machine in the index. The yielded {Entry} objects + # will NOT be locked, so you'll have to call {#get} manually to acquire + # the lock on them. + def each + @machines.each do |uuid, data| + yield Entry.new(uuid, data.merge("id" => uuid)) + end + end + # Accesses a machine by UUID and returns a {MachineIndex::Entry} # # The entry returned is locked and can't be read again or updated by diff --git a/test/unit/vagrant/machine_directory_test.rb b/test/unit/vagrant/machine_directory_test.rb index 7828f45e7..896c75575 100644 --- a/test/unit/vagrant/machine_directory_test.rb +++ b/test/unit/vagrant/machine_directory_test.rb @@ -10,6 +10,7 @@ describe Vagrant::MachineIndex do include_context "unit" let(:data_dir) { temporary_dir } + let(:entry_klass) { Vagrant::MachineIndex::Entry } subject { described_class.new(data_dir) } @@ -31,6 +32,35 @@ describe Vagrant::MachineIndex do to raise_error(Vagrant::Errors::CorruptMachineIndex) end + describe "#each" do + before do + 5.times do |i| + e = entry_klass.new + e.name = "entry-#{i}" + e.vagrantfile_path = "/foo" + subject.release(subject.set(e)) + end + end + + it "should iterate over all the elements" do + items = [] + + subject = described_class.new(data_dir) + subject.each do |entry| + items << entry.name + end + + items.sort! + expect(items).to eq([ + "entry-0", + "entry-1", + "entry-2", + "entry-3", + "entry-4", + ]) + end + end + describe "#get and #release" do before do data = { @@ -85,8 +115,6 @@ describe Vagrant::MachineIndex do end describe "#set and #get and #delete" do - let(:entry_klass) { Vagrant::MachineIndex::Entry } - let(:new_entry) do entry_klass.new.tap do |e| e.name = "foo"