首页 > 解决方案 > 我可以从基类添加派生类吗?

问题描述

我想为所有派生类添加模块。

但是写入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

标签: ruby

解决方案


推荐阅读