I figured it out a bit and came up with a solution. You said that you have a module in which you perform encryption. I assume the module is singleton. My solution, however, requires that you have an instance.
class Crypto def self.instance @__instance__ ||= new end end
Extract encryption behavior in the module.
module Encryptable def encrypt
Create a new module that handles exceptions.
module ExceptionHandler extend ActiveSupport::Concern included do include ActiveSupport::Rescuable rescue_from StandardError, :with => :known_error end def handle_known_exceptions yield rescue => ex rescue_with_handler(ex) || raise end def known_error(ex) Rails.logger.error "[ExceptionHandler] Exception #{ex.class}: #{ex.message}" end end
So now you can use the new handle_known_exceptions inside your Crypto . This is not very convenient because you won little. You should still call the exception handler inside each method:
class Crypto include ExceptionHandler def print_bunnies handle_known_exceptions do File.open("bunnies") end end end
It is not necessary to do this if we define a delegate who does this for us:
class CryptoDelegator include ExceptionHandler def initialize(target) @target = target end def method_missing(*args, &block) handle_known_exceptions do @target.send(*args, &block) end end end
Override Crypto initialization completely, use delegate instead.
class Crypto include Encryptable def self.new(*args, &block) CryptoDelegator.new(super) end def self.instance @__instance__ ||= new end end
What is it!
shime source share