Module: Eldritch::DSL

Defined in:
lib/eldritch/dsl.rb

Overview

Instance Method Summary collapse

Instance Method Details

#async(method = nil, &block) ⇒ Task

Creates an asynchronous method or starts an async block

If a block is passed, this will be an async block. Otherwise this method will create an async method.

When an async block is called, it will yield the block in a new thread.

async do
  # will run in parallel
end
#=> <Task>

When called, async methods behave exactly like async blocks.

async def foo
  # will run in parallel
end

foo
#=> <Task>

If you are using ruby < 2.1.0, you will need to define async methods like so:

def foo
  # will run in parallel
end
async :foo

Parameters:

  • method (Symbol) (defaults to: nil)

    the name of the async method.

Returns:

  • (Task)

    a task representing the async method or block (only for async block and async method call)



38
39
40
41
42
43
44
# File 'lib/eldritch/dsl.rb', line 38

def async(method=nil, &block)
  if block
    async_block(&block)
  else
    async_method(method)
  end
end

#sync(task) ⇒ Object

Allows async methods to be called like synchronous methods

sync send_email(42) # send_mail is async

Parameters:

Returns:

  • whatever the method has returned



52
53
54
# File 'lib/eldritch/dsl.rb', line 52

def sync(task)
  task.value
end

#together {|Group| ... } ⇒ Object

Creates a group of async call and blocks

When async blocks and calls are inside a together block, they can act as a group.

A together block waits for all the async call/blocks that were started within itself to stop before continuing.

together do
  5.times do
    async { sleep(1) }
  end
end
# waits for all 5 async blocks to complete

A together block will also yield a Group. This can be used to interact with the other async calls/blocks.

together do |group|
  5.times do
    async do
      # stop everyone else
      group.interrupt if something?
    end
  end
end

Yields:

  • (Group)

    group of async blocks/calls

See Also:



82
83
84
85
86
87
88
89
90
91
92
# File 'lib/eldritch/dsl.rb', line 82

def together
  old = Thread.current.eldritch_group

  group = Group.new
  Thread.current.eldritch_group = group

  yield group

  group.join_all
  Thread.current.eldritch_group = old
end