Created
January 29, 2015 11:21
-
-
Save awls99/dbfc0a95457a50b21c11 to your computer and use it in GitHub Desktop.
Error classes for lazy bums like myself example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#The following two examples are equivalent | |
#Example 1, explicit error classe declaration | |
class MyMainNamespace | |
module Errors | |
class Error1 < StandardError; end | |
class Error2 < StandardError; end | |
end | |
end | |
#Example 2, use const_missing for maximum lazyness | |
class MyMainNamespace | |
module Errors | |
def self.const_missing class_name | |
self.const_set( class_name , Class.new( StandardError ) ) | |
self.const_get( class_name ) | |
end | |
end | |
end | |
#usage: | |
being | |
do_something | |
rescue MyMainNamespace::Errors::Error1 | |
do_something_else | |
rescue MyMainNamespace::Errors::Error2 | |
do_something_different | |
#only works with second example, throws an invalid constant Error404 otherwise | |
rescue MyMainNamespace::Errors::Error404 | |
error_not_found | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment