Class: LoneWolf::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/lone_wolf.rb

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Worker

Returns a new instance of Worker.



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

def initialize(**options)
  loop! if options[:loop]
  @job = options[:job] if options[:job]
  @input_stream = Slipstream.create
  @output_stream = Slipstream.create
  if options[:start]
    started = start! 
    warn "Unable to start worker!" unless started
  end
end

Instance Method Details

#inputObject



71
72
73
# File 'lib/lone_wolf.rb', line 71

def input
  @input_stream
end

#job(&block) ⇒ Object



27
28
29
30
31
# File 'lib/lone_wolf.rb', line 27

def job(&block)
  return @job unless block_given?
  warn "Specifying the job now won't work unless you restart the worker!" if @pid
  @job = block
end

#job=(prc) ⇒ Object



22
23
24
25
# File 'lib/lone_wolf.rb', line 22

def job=(prc)
  warn "Specifying the job now won't work unless you restart the worker!" if @pid
  @job = prc
end

#job?Boolean

Returns:

  • (Boolean)


17
18
19
20
# File 'lib/lone_wolf.rb', line 17

def job?
  return true if @job
  false
end

#kill!Object



79
80
81
82
83
84
# File 'lib/lone_wolf.rb', line 79

def kill!
  return false if @pid.nil?
  @pid = nil if Process.kill('KILL', @pid) == 1
  return true if @pid.nil?
  false
end

#killed?Boolean

Returns:

  • (Boolean)


86
87
88
89
# File 'lib/lone_wolf.rb', line 86

def killed?
  return true if @pid.nil?
  false
end

#loop!Object



33
34
35
36
# File 'lib/lone_wolf.rb', line 33

def loop!
  warn "Specifying the loop now won't work unless you restart the worker!" if @pid
  @loop = true
end

#loop?Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/lone_wolf.rb', line 38

def loop?
  return true if @loop
  false
end

#outputObject



75
76
77
# File 'lib/lone_wolf.rb', line 75

def output
  @output_stream
end

#pidObject



91
92
93
# File 'lib/lone_wolf.rb', line 91

def pid
  @pid
end

#pid?Boolean

Returns:

  • (Boolean)


95
96
97
98
# File 'lib/lone_wolf.rb', line 95

def pid?
  return true if @pid
  false
end

#restart!Object



66
67
68
69
# File 'lib/lone_wolf.rb', line 66

def restart!
  kill!
  start!
end

#start!Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/lone_wolf.rb', line 43

def start!
  return false if @pid
  return false unless @job
  @pid = fork do
    trap "SIGINT" do
      exit 0
    end
    if loop?
      while true do
        iput = input.read
        next if iput.nil?
        iput = iput.strip
        next if iput.empty?
        result = @job.call(iput)
        output.write result
      end
    else
      output.write @job.call(input.read)
    end
  end
  return true 
end