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, task) ⇒ Worker

Returns a new instance of Worker.



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

def initialize(payload, task)
  @payload  = payload
  @task     = task
  @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

#payloadObject (readonly)

Returns the value of attribute payload.



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

def payload
  @payload
end

#taskObject (readonly)

Returns the value of attribute task.



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

def task
  @task
end

Instance Method Details

#callObject

It sends payload a message call and passes the result of task, by sending task 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

task 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
# File 'lib/async_io/worker.rb', line 44

def call
  try do
    @done = task.call
    payload.call(done).tap { @finished = true }
  end
end

#tryObject

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



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

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