Sha256: 0153201a1f56778272725207f9fe542b5e48a51a35d7f7ebaa8a8ea210054237

Contents?: true

Size: 1.75 KB

Versions: 2

Compression:

Stored size: 1.75 KB

Contents

require 'rubygems'
require 'eventmachine'

$cache_file = '/tmp/crossstub.cache'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'cross-stub'

class AnyClass
  def self.say_world
    'u say world'
  end
end

class AnyModule
  def self.say_world
    'u say world'
  end
end

module EchoClient

  class << self

    attr_accessor :result

    def get(klass_and_method)
      address, port = EchoServer::ADDRESS, EchoServer::PORT
      EventMachine::run do
        (EventMachine::connect(address, port, EM)).
          execute(klass_and_method) {|data| self.result = data }
      end
      (self.result == '<NIL>') ? nil : self.result
    end

  end

  private

    module EM
      def receive_data(data)
        @callback[data]
        EventMachine::stop_event_loop
      end
      def execute(method, &blk)
        @callback = blk
        send_data method
      end
    end

end

module EchoServer

  ADDRESS, PORT = '127.0.0.1', 8081

  class << self

    def pid
      @process.pid
    end

    def start(other_process=false)
      unless other_process
        @process = IO.popen("ruby #{__FILE__}")
        sleep 1
      else
        EventMachine::run { EventMachine::start_server(ADDRESS, PORT, EM) }
      end
    end

    def stop
      Process.kill('SIGHUP', pid)
    end

  end

  private

    module EM
      def receive_data(klass_and_method)
        CrossStub.refresh(:file => $cache_file)
        klass, method, *args = klass_and_method.split('.')
        value =
          if args.empty?
            Object.const_get(klass).send(method) rescue $!
          else
            Object.const_get(klass).send(method, *args) rescue $!
          end
        send_data(value.nil? ? '<NIL>' : value)
      end
    end

end

EchoServer.start(true) if ($0 == __FILE__)

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cross-stub-0.1.1 spec/helpers.rb
cross-stub-0.1.0 spec/helpers.rb