Module: EventMachine

Defined in:
lib/mind_control/em.rb

Class Method Summary collapse

Class Method Details

.__binding__Object

Context for Pry.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mind_control/em.rb', line 8

def self.__binding__
  @binding ||= EventMachine.send( :binding ).tap do |binding|
    orig_eval = binding.method( :eval )

    ##
    # Eval code in reactor context and return result.
    #
    binding.define_singleton_method :eval do |*args, &block|
      raise "Reactor not running!" unless EventMachine.reactor_running?

      # Channel between our and reactor threads
      queue = ::Queue.new

      # In reactor context
      EventMachine::next_tick do
        # In case of fibered code we should create Fiber
        Fiber.new {
          begin
            queue.push orig_eval.call( *args, &block )
          rescue Exception => e
            # Return errors too
            queue.push e
          end
        }.resume
      end

      # Wait for result
      return queue.pop.tap do |result|
        raise result if result.is_a?( Exception )
      end
    end
  end
end