Skip to content

Instantly share code, notes, and snippets.

@natesymer
Created September 25, 2014 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natesymer/7d763438828f62f902a8 to your computer and use it in GitHub Desktop.
Save natesymer/7d763438828f62f902a8 to your computer and use it in GitHub Desktop.
Adds default messages to Exception subclasses.
require "./with_message.rb"
MyError = StandardError.with_message "This is my error message"
raise MyError # the raised error's message is "This is my error message"
raise MyError, "Something else" # the raised error's message is "Something else"
#!/usr/bin/env ruby
class Exception
alias_method :initialize_original, :initialize
class << self
attr_accessor :default_message
def with_message msg
@global_message ||= nil
e = Class.new self
e.default_message = msg
e
end
end
def initialize msg=nil
initialize_original msg || self.class.default_message
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment