我可以优先使用基类的派生类吗?

时间:2019-06-28 09:13:10

标签: ruby

我想在所有派生类的前面添加模块。

但是很无聊,将prepend GenericFooException写入所有文件。

(阴郁的语气。)如何简单写法?

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

0 个答案:

没有答案