From 0c612f695f8b95bc95b5e6747e5c9dc3cd6d51d1 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 11 Jan 2013 15:44:35 -0800 Subject: [PATCH] Util::ScopedHashOverride --- lib/vagrant/util/scoped_hash_override.rb | 40 ++++++++++++++++ .../vagrant/util/scoped_hash_override_test.rb | 48 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 lib/vagrant/util/scoped_hash_override.rb create mode 100644 test/unit/vagrant/util/scoped_hash_override_test.rb diff --git a/lib/vagrant/util/scoped_hash_override.rb b/lib/vagrant/util/scoped_hash_override.rb new file mode 100644 index 000000000..ebb778799 --- /dev/null +++ b/lib/vagrant/util/scoped_hash_override.rb @@ -0,0 +1,40 @@ +module Vagrant + module Util + # This allows for hash options to be overridden by a scope key + # prefix. An example speaks best here. Imagine the following hash: + # + # original = { + # :id => "foo", + # :mitchellh__id => "bar", + # :mitchellh__other => "foo" + # } + # + # scoped = scoped_hash_override(original, "mitchellh") + # + # scoped == { + # :id => "bar", + # :other => "foo" + # } + # + module ScopedHashOverride + def scoped_hash_override(original, scope) + result = original.dup + + original.each do |key, value| + parts = key.to_s.split("__", 2) + + # If we don't have the proper parts, then bail + next if parts.length != 2 + + # If this is our scope, then override + if parts[0] == scope + result[parts[1].to_sym] = value + result.delete(key) + end + end + + result + end + end + end +end diff --git a/test/unit/vagrant/util/scoped_hash_override_test.rb b/test/unit/vagrant/util/scoped_hash_override_test.rb new file mode 100644 index 000000000..bdf277503 --- /dev/null +++ b/test/unit/vagrant/util/scoped_hash_override_test.rb @@ -0,0 +1,48 @@ +require File.expand_path("../../../base", __FILE__) + +require "vagrant/util/scoped_hash_override" + +describe Vagrant::Util::ScopedHashOverride do + let(:klass) do + Class.new do + extend Vagrant::Util::ScopedHashOverride + end + end + + it "should not mess with non-overrides" do + original = { + :key => "value", + :another_value => "foo" + } + + klass.scoped_hash_override(original, "foo").should == original + end + + it "should override if the scope matches" do + original = { + :key => "value", + :scope__key => "replaced" + } + + expected = { + :key => "replaced" + } + + klass.scoped_hash_override(original, "scope").should == expected + end + + it "should ignore non-matching scopes" do + original = { + :key => "value", + :scope__key => "replaced", + :another__key => "value" + } + + expected = { + :key => "replaced", + :another__key => "value" + } + + klass.scoped_hash_override(original, "scope").should == expected + end +end