From 00f61e67e109bbc8db90720ef27af349a71d8a67 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 1 Oct 2013 21:45:05 -0700 Subject: [PATCH] core: errors can use error_message to specify string error message --- lib/vagrant/errors.rb | 15 ++++++++++++++- templates/locales/en.yml | 1 + test/unit/vagrant/errors_test.rb | 33 ++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 test/unit/vagrant/errors_test.rb diff --git a/lib/vagrant/errors.rb b/lib/vagrant/errors.rb index 7ec3ca7b0..d5916cd7d 100644 --- a/lib/vagrant/errors.rb +++ b/lib/vagrant/errors.rb @@ -48,6 +48,10 @@ module Vagrant error_namespace(namespace) if namespace end + def self.error_message(message) + define_method(:error_message) { message } + end + def self.error_namespace(namespace) define_method(:error_namespace) { namespace } end @@ -55,11 +59,20 @@ module Vagrant def initialize(message=nil, *args) message = { :_key => message } if message && !message.is_a?(Hash) message = { :_key => error_key, :_namespace => error_namespace }.merge(message || {}) - message = translate_error(message) + + if error_key + message = translate_error(message) + else + message = error_message + end super end + # The error message for this error. This is used if no error_key + # is specified for a translatable error message. + def error_message; "No error message"; end + # The default error namespace which is used for the error key. # This can be overridden here or by calling the "error_namespace" # class method. diff --git a/templates/locales/en.yml b/templates/locales/en.yml index 94288ce27..1f82cfb14 100644 --- a/templates/locales/en.yml +++ b/templates/locales/en.yml @@ -572,6 +572,7 @@ en: Port: %{port} Username: %{username} Private key: %{key_path} + test_key: "test value" ui_expects_tty: |- Vagrant is attempting to interface with the UI in a way that requires a TTY. Most actions in Vagrant that require a TTY have configuration diff --git a/test/unit/vagrant/errors_test.rb b/test/unit/vagrant/errors_test.rb new file mode 100644 index 000000000..bbd7610cf --- /dev/null +++ b/test/unit/vagrant/errors_test.rb @@ -0,0 +1,33 @@ +require File.expand_path("../../base", __FILE__) + +describe Vagrant::Errors::VagrantError do + describe "subclass with error key" do + let(:klass) do + Class.new(described_class) do + error_key("test_key") + end + end + + subject { klass.new } + + it "should use the translation for the message" do + subject.to_s.should == "test value" + end + + its("status_code") { should eq(1) } + end + + describe "subclass with error message" do + let(:klass) do + Class.new(described_class) do + error_message("foo") + end + end + + subject { klass.new } + + it "should use the translation for the message" do + subject.to_s.should == "foo" + end + end +end