Class: DeferProc

Inherits:
Object
  • Object
show all
Defined in:
lib/defer_proc.rb,
lib/defer_proc/version.rb

Overview

Class to defer execution of a block

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(interval = 0.1, &block) ⇒ DeferProc

Initialize with the block for deferred execution



7
8
9
10
11
12
13
14
15
16
# File 'lib/defer_proc.rb', line 7

def initialize(interval=0.1, &block)
  # `Procrastinate` requires a block be passed to initialization
  throw ArgumentError.new("DeferProc must be initialized with a block") if block.nil?
  # Interval must be a positive number
  throw ArgumentError.new("Polling interval must be a number.") unless interval.is_a? Numeric
  throw ArgumentError.new("Polling interval must be positive.") unless interval > 0

  @interval = interval
  @deferred_block = block
end

Instance Method Details

#until(&conditional) ⇒ Object

Defer execution until the provided block is satisfied



19
20
21
22
23
24
25
26
# File 'lib/defer_proc.rb', line 19

def until(&conditional)
  # `DeferProc#until` must be passed a conditional block
  throw ArgumentError.new("A conditional block is required") if conditional.nil?

  # forward the (negated) block to `DeferProc#while`
  conditional_proc = Proc.new { not conditional.call }
  self.while(&conditional_proc)
end

#while(&conditional) ⇒ Object

Defer execution of the @deferred_block while the provided block is satisfied



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/defer_proc.rb', line 29

def while(&conditional)
  # `DeferProc#while` must be passed a conditional block
  throw ArgumentError.new("A conditional block is required") if conditional.nil?

  Thread.new {
    # Lower the priority for the polling thread
    Thread.current.priority = -2

    while yield do
      # Poll ever `@interval` seconds until the conditional block is satisfied.
      sleep @interval
    end
    # Call the deferred block
    @deferred_block.call
  }
end