Module: MuchTimeout

Defined in:
lib/much-timeout.rb,
lib/much-timeout/version.rb

Constant Summary collapse

TimeoutError =

rubocop:disable Lint/InheritException

Class.new(Interrupt)
PIPE_SIGNAL =
"."
VERSION =
"0.1.2"

Class Method Summary collapse

Class Method Details

.just_optional_timeout(seconds, args) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/much-timeout.rb', line 82

def self.just_optional_timeout(seconds, args)
  args ||= {}
  if args[:do].nil?
    raise ArgumentError, "you need to specify a :do block arg to call"
  end
  unless args[:do].is_a?(::Proc)
    raise ArgumentError, "you need pass a Proc as the :do arg " \
                         "(`#{args[:do].inspect}` was given)"
  end

  if !seconds.nil?
    just_timeout(seconds, args)
  else
    args[:do].call
  end
end

.just_timeout(seconds, args) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/much-timeout.rb', line 61

def self.just_timeout(seconds, args)
  args ||= {}
  if args[:do].nil?
    raise ArgumentError, "you need to specify a :do block arg to call"
  end
  unless args[:do].is_a?(::Proc)
    raise ArgumentError, "you need pass a Proc as the :do arg " \
                         "(`#{args[:do].inspect}` was given)"
  end
  if !args[:on_timeout].nil? && !args[:on_timeout].is_a?(::Proc)
    raise ArgumentError, "you need pass a Proc as the :on_timeout arg " \
                         "(`#{args[:on_timeout].inspect}` was given)"
  end

  begin
    timeout(seconds, &args[:do])
  rescue TimeoutError
    (args[:on_timeout] || proc{}).call
  end
end

.optional_timeout(seconds, klass = nil, &block) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/much-timeout.rb', line 53

def self.optional_timeout(seconds, klass = nil, &block)
  if !seconds.nil?
    timeout(seconds, klass, &block)
  else
    block.call
  end
end

.timeout(seconds, klass = nil, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/much-timeout.rb', line 11

def self.timeout(seconds, klass = nil, &block)
  if seconds.nil?
    raise ArgumentError, "please specify a non-nil seconds value"
  end
  unless seconds.is_a?(::Numeric)
    raise ArgumentError, "please specify a numeric seconds value " \
                         "(`#{seconds.inspect}` was given)"
  end
  exception_klass = klass || TimeoutError
  reader, writer  = IO.pipe

  begin
    main_thread = Thread.current
    io_select_thread ||= Thread.new do
      unless ::IO.select([reader], nil, nil, seconds)
        main_thread.raise exception_klass
      end
    end
    begin
      block.call
    ensure
      begin
        writer.write_nonblock(PIPE_SIGNAL)
      rescue
        false
      end
      io_select_thread.join
    end
  ensure
    begin
      reader.close
    rescue
      false
    end
    begin
      writer.close
    rescue
      false
    end
  end
end