Created
December 2, 2012 18:34
-
-
Save ngarbezza/4190355 to your computer and use it in GitHub Desktop.
Smalltalk exception handling for Ruby 1.9.x
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
class Proc | |
def on(exception_class) | |
begin | |
self.call | |
rescue exception_class => e | |
yield e | |
end | |
end | |
end |
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
describe Proc do | |
describe "smalltalk exception handling style" do | |
it "should execute a block normally" do | |
evaluated = false | |
-> { evaluated = true }.on StandardError do | |
fail 'no exception occurred, so this block does not have to evaluated' | |
end | |
evaluated.should be_true | |
end | |
it "should catch an exception and evaluate the corresponding block" do | |
evaluated = false | |
-> { raise StandardError }.on StandardError do | |
evaluated = true | |
end | |
evaluated.should be_true | |
end | |
it "should not catch an exception for a different handler" do | |
class MyCustomError < StandardError; end | |
expect { | |
-> { raise StandardError }.on MyCustomError { } | |
}.to raise_error(StandardError) | |
end | |
it "should pass as argument the exception object" do | |
-> { | |
raise StandardError, 'the message' | |
}.on StandardError do |exception_object| | |
exception_object.message.should == 'the message' | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment