Skip to content

Instantly share code, notes, and snippets.

@panthomakos
Created September 20, 2011 21:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panthomakos/1230515 to your computer and use it in GitHub Desktop.
Save panthomakos/1230515 to your computer and use it in GitHub Desktop.
Dynamic Exception Rescue in Ruby
#!/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
#!/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
#!/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
@evie404
Copy link

evie404 commented Mar 27, 2014

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 :<

@rmg
Copy link

rmg commented Sep 12, 2014

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 :-)

@akostadinov
Copy link

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