Module: ExecutionDeadline::Helpers

Defined in:
lib/execution_deadline/helpers.rb

Constant Summary collapse

UNWRAPPED_METHOD_NAME_SUFFIX =
"_without_deadline"
WRAPPED_METHOD =
Proc.new do |options|
  Proc.new do |*args, &blk|
    set_deadline = options[:in]  && ExecutionDeadline.set_deadline(
      expires_at: Time.now + options[:in],
      raises: options[:raises]
    )

    ExecutionDeadline.current_deadline&.require_seconds_left!(options[:runs_for]) if options[:runs_for]
    send(options[:aliased_method_name], *args, &blk).tap do
      ExecutionDeadline.current_deadline&.check_deadline_expiration!
    end
  ensure
    ExecutionDeadline.clear_deadline! if set_deadline
  end
end

Instance Method Summary collapse

Instance Method Details

#deadline(options = {}) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/execution_deadline/helpers.rb', line 25

def deadline(options = {})
  options[:in] ||
    options[:runs_for] ||
    raise('expected deadline to include either :in or :runs_for')

  @last_deadline_config = options
end

#method_added(method_name) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/execution_deadline/helpers.rb', line 33

def method_added(method_name)
  return super unless _has_deadline_config?

  options = _fetch_and_reset_deadline_config
  options[:aliased_method_name] ||= "_#{method_name}#{UNWRAPPED_METHOD_NAME_SUFFIX}".to_sym

  alias_method options[:aliased_method_name], method_name

  define_method(method_name, &WRAPPED_METHOD.call(options))
end

#singleton_method_added(method_name) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/execution_deadline/helpers.rb', line 44

def singleton_method_added(method_name)
  return super unless _has_deadline_config?

  options = _fetch_and_reset_deadline_config

  options[:aliased_method_name] ||= "_#{method_name}#{UNWRAPPED_METHOD_NAME_SUFFIX}".to_sym

  singleton_class.class_eval do
    alias_method options[:aliased_method_name], method_name
  end

  define_singleton_method(method_name, &WRAPPED_METHOD.call(options))
end