Module: SlippyMethodHooks::ClassMethods

Defined in:
lib/slippy_method_hooks/hooks.rb

Instance Method Summary collapse

Instance Method Details

#after(*names, &blk) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 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) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 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) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 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) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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