Can I prepend to derived classes from base class?

故事扮演 提交于 2021-01-29 10:54:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!