module SlippyMethodHooks::ClassMethods

Public Instance Methods

after(*names, &blk) click to toggle source
# File lib/slippy_method_hooks/hooks.rb, line 64
def after(*names, &blk)
  unless blk
    raise NoBlockGiven,
          '.rescue_on_fail must be called with a block',
          caller
  end
  names.each do |name|
    meth = instance_method(name)
    define_method name do |*args, &block|
      result = meth.bind(self).call(*args, &block)
      instance_exec(result, &blk)
    end
  end
end
before(*names, &blk) click to toggle source
# File lib/slippy_method_hooks/hooks.rb, line 49
def before(*names, &blk)
  unless blk
    raise NoBlockGiven,
          '.rescue_on_fail must be called with a block',
          caller
  end
  names.each do |name|
    meth = instance_method(name)
    define_method name do |*args, &block|
      instance_exec(name, *args, block, &blk)
      meth.bind(self).call(*args, &block)
    end
  end
end
rescue_on_fail(*names, &blk) click to toggle source
# File lib/slippy_method_hooks/hooks.rb, line 31
def rescue_on_fail(*names, &blk)
  unless blk
    raise NoBlockGiven,
          '.rescue_on_fail must be called with a block',
          caller
  end
  names.each do |name|
    meth = instance_method(name)
    define_method(name) do |*args, &block|
      begin
        meth.bind(self).call(*args, &block)
      rescue StandardError => e
        instance_exec(e, &blk)
      end
    end
  end
end
time_box_method(time, *names, &blk) click to toggle source
# File lib/slippy_method_hooks/hooks.rb, line 13
def time_box_method(time, *names, &blk)
  names.each do |name|
    meth = instance_method(name)
    define_method(name) do |*args, &block|
      begin
        Timeout.timeout(time) do
          meth.bind(self).call(*args, &block)
        end
      rescue Timeout::Error
        error_args = [TimeoutError, 'execution expired', caller]
        raise(*error_args) unless block_given?

        instance_exec(*error_args, &blk)
      end
    end
  end
end