Created
September 20, 2011 21:50
-
-
Save panthomakos/1230515 to your computer and use it in GitHub Desktop.
Dynamic Exception Rescue in Ruby
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
#!/usr/bin/env ruby | |
def match_message(regexp) | |
m = Module.new | |
(class << m; self; end).instance_eval do | |
define_method(:===) do |error| | |
regexp === error.message | |
end | |
end | |
m | |
end | |
begin | |
raise StandardError, "Error message about a socket." | |
rescue match_message(/socket/) => error | |
puts "Error #{error.class.name} matches /socket/; ignored." | |
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
#!/usr/bin/env ruby | |
def match_message(regexp) | |
lambda{ |error| regexp === error.message } | |
end | |
begin | |
raise StandardError, "Error message about a socket." | |
rescue match_message(/socket/) => error | |
puts "Error #{error.class.name} matches /socket/; ignored." | |
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
#!/usr/bin/env ruby | |
require 'benchmark' | |
def match_message192(regexp) | |
lambda{ |error| regexp === error.message } | |
end | |
def match_message187(regexp) | |
m = Module.new | |
(class << m; self; end).instance_eval do | |
define_method(:===) do |error| | |
regexp === error.message | |
end | |
end | |
m | |
end | |
Benchmark.bm do |x| | |
x.report { 100_000.times{ match_message192(/socket/); } } | |
x.report { 100_000.times{ match_message187(/socket/); } } | |
end |
For anyone reaching this page from Google, the 1.8.7 version (straight out of Exceptional Ruby, buy it!) works fine in 2.1.2 :-)
It only appears to work on 1.9.x, something seems to have changed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just came across this. I tried the lambda approach and and getting TypeError in Ruby 2.1.1. It appears that this support has been removed :<