Class: AsyncIO::Worker

Inherits:
Object
  • Object
show all
Includes:
Rescuer
Defined in:
lib/async_io/worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Rescuer

#rescuer

Constructor Details

#initialize(payload, job) ⇒ Worker

Returns a new instance of Worker.



12
13
14
15
16
17
# File 'lib/async_io/worker.rb', line 12

def initialize(payload, job)
  @payload  = payload
  @job      = job
  @done     = false
  @finished = false
end

Instance Attribute Details

#doneObject (readonly)

Returns the value of attribute done.



10
11
12
# File 'lib/async_io/worker.rb', line 10

def done
  @done
end

#finishedObject (readonly)

Returns the value of attribute finished.



10
11
12
# File 'lib/async_io/worker.rb', line 10

def finished
  @finished
end

#jobObject (readonly)

Returns the value of attribute job.



9
10
11
# File 'lib/async_io/worker.rb', line 9

def job
  @job
end

#payloadObject (readonly)

Returns the value of attribute payload.



9
10
11
# File 'lib/async_io/worker.rb', line 9

def payload
  @payload
end

Instance Method Details

#callObject

It sends payload a message call and passes the result of a job, by sending job a message call as well, as its argument. This allows us to do:

aget_user(1) { |u| print u.name }

> Paul Clark Manson

Or any other sort of task that you may need its result to be available within a block without needing to wait for it to finish and non blocking IO.

A payload is a Ruby object must pass, for example:

payload = lambda { |u| print u.name } payload = Object.new def payload.call(result); warn(result); end

job is pre-definied inside a method, it can be anything, for example: worker(payload) do

User.find(uid)

end



44
45
46
47
48
49
50
# File 'lib/async_io/worker.rb', line 44

def call
  try do
    @finished = true
    @done = job.call
    payload.call(done)
  end
end

#tryObject

Tries to get the first job done, when an exception is raised it then calls payload again passing a fallback as its argument.



57
58
59
60
61
62
63
# File 'lib/async_io/worker.rb', line 57

def try
  begin
    yield
  rescue Exception => notice
    rescuer { payload.call(fallback(notice)) }
  end
end