问题
I want prepend module to all derived classes.
But boring that writes prepend GenericFooException
to all files.
(gloomy tone.) How to easy way to write?
module GenericFooException
class FooException < StandardError; end
def perform
super
rescue FooException => e
# The truth is that rails ActiveRecord::ActiveRecordError with .cause
puts "[CATCH] #{e.class}"
end
end
module Foo
class Base
prepend GenericFooException
def perform
raise RuntimeError
end
end
end
# It is my best. but can not catch the FooException
module Foo
class Alice < Base
class AliceException < FooException; end
def perform
raise AliceException
end
end
end
# Work it.
module Foo
class Bob < Base
prepend GenericFooException
class BobException < FooException; end
def perform
raise BobException
end
end
end
Foo::Alice.new.perform #=> (exception)Foo::Alice::AliceException
Foo::Bob.new.perform #=> (output)[CATCH] Foo::Bob::BobException
来源:https://stackoverflow.com/questions/56804098/can-i-prepend-to-derived-classes-from-base-class